// pages/addperson/addperson.js
const app = getApp()
const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var util = require('../../utils/util');


var util1 = require('../../utils/util1');
const config = require('../../config')
const plugin = requirePlugin("myPlugin")


var methods = require('../../utils/methods');
var md5 = require('../../utils/md5.js');
var bleall = require('../../utils/bleall');
import moment from "../../utils/moment"
import {
  BLE
} from "../../utils/btls/ble";
const emitter = app.globalData.emitter
const ADD_NFC_MODE = 10
// 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() + 3; //年
  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 += '23:59:59';
  return (clock);
}
var date = new Date()
var isConnected = false
var connectedDeviceId = ''
var basecode = 29283991
var lockId = 1
var lockManagerId = 1
var lockMac = ''
var isInitReady = false
var lockModel
var lockDevice
var taskId = 0

var pincode = -1
var pincodeIndex = -1

var rfCardId = -1
var rfCardIndex = -1

var fingerprintIndex = -1
var passwordLiAll = {
  id: ''
}
var isLockLogin = false
var serialNumber = ''
let letterRandom = [
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];

function randomMethods() {
  let str = ''
  for (let i = 0; i < 8; i++) {
    str +=
      letterRandom[Math.round(Math.random() * (letterRandom.length - 1))];
  }
  return str
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isBindLock: false,
    isPincodeAdd: false,
    isRfCardAdd: false,
    isFingerprintAdd: false,
    isUnloked: false,
    isMuted: false,
    isNbEnable: true,
    lockModel: 0,
    lock: {},
    isSearch: app.globalData.isSearch,

    activeKey: 0,
    NfcList: [],
    FpList: [],
    passwordList: [],
    show: false,
    datetimerange: [CurentTime(), CurentTime1()],
    minDate: '',
    minDate1: '',
    endtime: '',
    starttime: '',
    addIndex: 0,
    pzname: '',
    current: '',
    currentIndex: '',
    fingerprintId: '',
    backstatus: false,
    radioDetil: '',
    passwordStatus: true,
    items: [{
        value: '0',
        name: '左手大拇指',
        checked: false
      },
      {
        value: '1',
        name: '左手食指',
        checked: false
      },
      {
        value: '2',
        name: '右手大拇指',
        checked: false
      },
      {
        value: '3',
        name: '右手食指',
        checked: false
      }
    ],
    showLoading: false,
    requestSatatus: true,
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var cgInfo = wx.getStorageSync('cgInfo')
    var deviceinfo = wx.getStorageSync('deviceinfo')
    var personLi = wx.getStorageSync('personLi')
    let minDate = wx.getStorageSync('minDate')
    let minDate1 = wx.getStorageSync('minDate1')
    this.setData({
      cgInfo: cgInfo,
      minDate,
      minDate1,
      starttime: minDate,
      endtime: minDate1,
      deviceinfo: deviceinfo,
      personLi: personLi,
      isSearch: false
    })
    this.getPassword()
    this.getNfc()
    this.getCarId()
    this.getFp()
    if (deviceinfo.manufactureId == 1201) {
      this.searchDevicesMethods()
    } else if (deviceinfo.manufactureId == 101) {
      app.watch(this.getcartcount, 'backdata')
      app.watch(this.fingerprintFun, 'fingerprintId')
    }
  },
  // 指纹选择
  radioChange(e) {
    var personLi = wx.getStorageSync('personLi')
    var pzname = ''
    if (e.detail.value == 0) {
      pzname = "左手大拇指"
    } else if (e.detail.value == 1) {
      pzname = "左手食指"
    } else if (e.detail.value == 2) {
      pzname = "右手大拇指"
    } else if (e.detail.value == 3) {
      pzname = "右手食指"
    }
    this.setData({
      radioDetil: pzname
    })
    this.getfingerprintMrhods(pzname, personLi.cardId, 11)
  },
  getfingerprintMrhods(pzname, id, type) {
    var that = this
    var items = [{
        value: '0',
        name: '左手大拇指',
        checked: false
      },
      {
        value: '1',
        name: '左手食指',
        checked: false
      },
      {
        value: '2',
        name: '右手大拇指',
        checked: false
      },
      {
        value: '3',
        name: '右手食指',
        checked: false
      }
    ]
    var data = {
      pageNum: 0,
      pageSize: 0,
      orderBy: "create_at desc",
      q: {
        cardId: id,
        types: type,
        deviceNum: this.data.deviceinfo.deviceNum,
        inStatus: '0,1,702'
      },
    };
    WXAPI.getCertificates(data).then(res => {
      var dataOne = util.zlib_unzip(res.data)
      if (res.success) {
        dataOne.map(li => {
          var content = JSON.parse(li.content)
          if (content.fingerprintAlias == pzname) {
            wx.showModal({
              title: '提示',
              content: '该指纹已存在，请选择其他',
              success(res1) {
                if (res1.confirm) {
                  console.log('用户点击确定')
                  that.setData({
                    items,
                    radioDetil: ''
                  })
                } else if (res1.cancel) {
                  console.log('用户点击取消')
                  that.setData({
                    items,
                    radioDetil: ''
                  })
                }
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: '获取失败',
          mask: true,
          duration: '2000',
          icon: 'none'
        })
      }
    })
  },
  fingerprintFun() {
    this.data.fingerprintId = app.globalData.fingerprintId
  },
  getcartcount(val) {
    var that = this
    var _this = this
    let deviceNum = that.data.deviceinfo.deviceNum
    var timestamp = moment().format("x")
    wx.showLoading({
      title: '添加指纹中',
      mask: true
    })
    if (app.globalData.backdata == 3 && this.data.backstatus) {
      bleall.startFp_29(deviceNum, 0x02, timestamp, function (res) {})
    } else if (app.globalData.backdata == 2 && this.data.backstatus) {
      bleall.startFp_29(deviceNum, 0x01, timestamp, function (res) {})
    } else if (app.globalData.backdata == 1 && this.data.backstatus) {
      console.log(app.globalData.backdata, this.data.backstatus, 'app.globalData.backdata, this.data.backstatus', this.data.fingerprintId)
      if (this.data.fingerprintId != 255) {
        var info = JSON.parse(this.data.personLi.info)
        var time1 = moment(this.data.datetimerange[0]).format("YYYYMMDDHHmmss")
        var time2 = moment(this.data.datetimerange[1]).format("YYYYMMDDHHmmss")
        var time3 = new Date(this.data.datetimerange[0].replace(/-/g, '/'))
        var time4 = new Date(this.data.datetimerange[1].replace(/-/g, '/'))
        var passwordStartTime = time3.getTime() / 1000
        var passwordEndTime = time4.getTime() / 1000
        var data = {
          managerTelephone: "18270949468",
          managerPassword: "202108",
          userTelephone: info.userTelephone,
          userPassword: info.userPassword,
          startTime: time1,
          endTime: time2
        }
        console.log(data, this.data.fingerprintId)
        // if(app.globalData.fingerprintId != -1){
        // setTimeout(() => {
        // app.globalData.backdata = -1
        this.setData({
          backstatus: false
        })
        let fingerprintId = ''
        console.log(_this.data.fingerprintId, typeof (_this.data.fingerprintId))
        if (Number(_this.data.fingerprintId) < 9) {
          fingerprintId = '0' + _this.data.fingerprintId.toString(16)
        } else {
          fingerprintId = _this.data.fingerprintId.toString(16)
        }
        let deviceinfo = that.data.deviceinfo
        bleall.startFp_63(data.managerTelephone, data.managerPassword, data.userTelephone, data.userPassword,
          data.startTime, data.endTime, 16, this.data.fingerprintId, timestamp,
          function (res) {
            console.log(res, 'resres')
            if (res.success) {
              wx.hideLoading()
              var cardName = '',
                pzname = ''
              if (that.data.pzname) {
                cardName = that.data.personLi.name + '-蓝牙-' + that.data.pzname
                pzname = '蓝牙-' + that.data.pzname
              } else {
                cardName = that.data.personLi.name + '-蓝牙-指纹' + that.data.FpList.length + 1
                pzname = '蓝牙-指纹' + that.data.FpList.length + 1
              }
              var str = {
                // cardId: this.personInfo.cardId,
                imei: _this.data.deviceinfo.imei,
                pzname: pzname,
                password: '',
                userTelephone: info.userTelephone,
                operateMode: 16,
                fingerprintAlias: _this.data.radioDetil,
                userPassword: info.userPassword,
                passwordStartTime: time1,
                passwordEndTime: time2,
                is: false,
                pass: true
              }
              var data3 = {
                code: "ble/operateUserInfo",
                data: {
                  deviceNum: deviceinfo.deviceNum,
                  imei: deviceinfo.imei,
                  userTelephone: info.userTelephone,
                  userPassword: info.userPassword,
                  password: fingerprintId,
                  userStartTime: time1,
                  userEndTime: time2,
                  passwordStartTime: time1,
                  passwordEndTime: time2,
                  operateMode: 16,
                  order: 6216,
                  timestamp: timestamp,
                  managerTelephone: '18270949468',
                  managerPassword: '202108',
                  passwordLength: 10,
                  permission: 4294967295,
                  times: 255,
                  recycleTime: "65535",
                  roomName: _this.data.deviceinfo.roomName,
                  cardName: cardName,
                }
              }
              console.log(data3, 'pppppp')
              WXAPI.sendCommand(data3).then(res3 => {
                console.log(res3, 'resres3')
                if (res3.success) {
                  var data4 = {
                    result: 1,
                    serial: res3.data.serialNumber
                  }
                  WXAPI.updatePush(data4).then(res4 => {

                  })
                  var data6 = {
                    result: 1,
                    serial: res3.data.serialNumber,
                    face: fingerprintId
                  }
                  WXAPI.editPushBySerial(data6).then(res4 => {

                  })
                  var data = {
                    cardId: _this.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    deviceNum: _this.data.deviceinfo.deviceNum,
                    type: 1,
                    imei: _this.data.deviceinfo.imei,
                    serial: res3.data.serialNumber,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  var datalist = {
                    cardId: _this.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 11,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  WXAPI.addCertificates(datalist).then(res6 => {})
                  console.log(data, '添加凭证')
                  WXAPI.addCertificates(data).then(res4 => {
                    if (res4.success) {
                      var updatedata = {
                        id: res4.data,
                        status: 1
                      };
                      WXAPI.updateCertificates(updatedata).then((res2) => {});
                      console.log(res3, '添加凭证成功')
                      _this.getFp()
                      _this.setData({
                        show: false
                      })
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加成功',
                        icon: 'none',
                        mask: true,
                        duration: 2000
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })

                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: res3.msg,
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '添加失败',
                duration: 2000,
                icon: 'none'
              })
            }
            if (res.data == "蓝牙功能暂不支持") {
              _this.startconnect()
            }
          })
        // }, 200)					
        // }
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '添加失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    }
  },
  // 删除开锁方式
  delMode(e) {
    var current = e.currentTarget.dataset.current
    var index = e.currentTarget.dataset.index
    var cgInfo = this.data.cgInfo
    var deviceinfo = this.data.deviceinfo
    this.setData({
      current: current,
      currentIndex: index
    })
    if (deviceinfo.manufactureId == 101) {
      if (current == 1) {
        this.delPassword1(index)
      } else if (current == 2) {
        this.delNfc1(index)
      } else if (current == 3) {
        this.delFp1(index)
      }
    } else if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      if (current == 1) {
        this.delPassword(index)
      } else if (current == 2) {
        this.delNfc1(index)
      } else if (current == 3) {
        this.delFp(index)
      }
    } else if (deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241) {
      if (this.data.isSearch) {
        if (current == 1) {
          this.delPasswordLwj(index)
        } else if (current == 2) {
          this.delNfcLwj(index)
        } else if (current == 3) {
          this.delFpLwj(index)
        }
      }else{
        this.searchDevicesMethods()
      }
    }
  },
  getNFCIndexLwj(index, callback) {
    var data = {
      q: JSON.stringify({
        cardId: this.data.personLi.cardId,
        inStatus: "1",
        types: '3',
        deviceNum: this.data.NfcList[index].deviceNum,
        // this.data.NfcList[index].serial,
        // result:1
      }),
      pageNum: 1,
      pageSize: 10,
      orderBy: "create_at desc"
    };
    WXAPI.getCertificates(data).then(res => {
      if (res.success) {
        var dataOne = util.zlib_unzip(res.data)
        console.log(dataOne, 'ddd')
        callback(dataOne)
      } else {
        wx.showToast({
          title: '获取失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  getNFCIndex(index, callback) {
    var data = {
      q: JSON.stringify({
        serial: this.data.NfcList[index].serial,
        result: 1
      }),
      pageNum: 1,
      pageSize: 10,
    };
    WXAPI.getDeviceResult(data).then(res => {
      if (res.success) {
        var dataOne = util.zlib_unzip(res.data)
        console.log(dataOne, 'ddd')
        callback(dataOne)
      } else {
        wx.showToast({
          title: '获取失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  getFpIndex(index, callback) {
    var data = {
      q: JSON.stringify({
        serial: this.data.FpList[index].serial,
      }),
      pageNum: 1,
      pageSize: 10,
    };
    WXAPI.getDeviceResult(data).then(res => {
      if (res.success) {
        var dataOne = util.zlib_unzip(res.data)
        console.log(dataOne, 'ddd')
        callback(dataOne)
      } else {
        wx.showToast({
          title: '获取失败',
          duration: 2000,
          mask: true,
          icon: 'none'
        })
      }
    })
  },
  addPassword(e) {
    this.setData({
      show: true,
      current: e.currentTarget.dataset.current,
      addIndex: e.currentTarget.dataset.addindex
    })
  },
  onChange1(event) {
    // event.detail 为当前输入的值
    this.setData({
      password: event.detail
    })
  },
  onChange2(event) {
    // event.detail 为当前输入的值
    this.setData({
      pzname: event.detail
    })
  },
  bindDateChange: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[0] = str
    this.setData({
      starttime: str,
    })
  },
  bindDateChange1: function (e) {
    var str = e.detail.value + " 23:59:59"
    this.data.datetimerange[1] = str
    this.setData({
      endtime: str
    })
  },
  delNfc1(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var cgInfo = this.data.cgInfo
    var personLi = this.data.NfcList[index]
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(personLi.content)
    var personInfo = JSON.parse(this.data.personLi.info)
    var _this = this
    this.getNFCIndex(index, function (data) {
      console.log(data, 'datatdatata', data[0])
      if (data.length > 0 && data[0].face != null) {
        var FPindex = data[0].face
        var dataPasswod = {
          code: "zg/cardOperate",
          data: {
            lockerId: deviceinfo.deviceNum,
            imei: deviceinfo.imei,
            lockerUserId: personInfo.userId,
            keyId: personInfo.userId,
            action: 2,
            taskStatus: 1,
            cardType: 50,
            cardNo: info.password,
            cardIndex: FPindex,
            startTime: personLi.startTime,
            endTime: personLi.endTime,
            order: 6212,
            type: 12,
            roomName: _this.data.deviceinfo.roomName,
            cardName: _this.data.personLi.name + personLi.pzname,
          }
        }
        WXAPI.sendCommand(dataPasswod).then(res => {
          console.log(res, '获取索引', FPindex)
          if (res.success) {
            var serialNumber = res.data.serialNumber
            var fingerNo = FPindex.toString(16)
            if (fingerNo.length == 1) {
              fingerNo = '0' + fingerNo
            } else {
              fingerNo = fingerNo
            }
            ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
              (callback) => {
                console.log(callback, fingerNo)
                if (callback.status == '00') {
                  ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, callback.signKey, (callback1) => {
                    console.log(callback1)
                    if (callback1.status == '00') {
                      var startTime = personLi.startTime.toString(16).toUpperCase()
                      var endTime = personLi.endTime.toString(16).toUpperCase()
                      console.log(cgInfo.lockerId, cgInfo.superId, personInfo.userId, personInfo.userId, fingerNo.toUpperCase(), '--', '01', callback.signKey, startTime, endTime, callback1.commonKey)
                      ICINLocker.modifyRFCard(cgInfo.lockerId, cgInfo.superId, personInfo.userId, personInfo.userId, fingerNo.toUpperCase(), '', '01', callback.signKey, startTime, endTime, callback1.commonKey, (
                        callback2) => {
                        console.log(callback2)
                        if (callback2.status == '00') {
                          var datacom = {
                            code: "zg/bleSendVoucherReply",
                            data: {
                              lockerId: deviceinfo.deviceNum,
                              serialNumber: serialNumber,
                              index: FPindex,
                              type: 12,
                              result: 1
                            }
                          }
                          WXAPI.sendCommand(datacom).then(res2 => {
                            console.log(res2, '成功----')
                          })
                          wx.showToast({
                            title: '下发成功',
                            mask: true,
                            icon: 'none',
                            duration: 2000
                          })
                          var data = {
                            ids: [personLi.id]
                          }
                          wx.hideLoading()
                          WXAPI.deleteCertificates(data).then(res1 => {
                            if (res1.success) {
                              _this.getNfc()
                              wx.showToast({
                                title: '删除成功',
                                mask: true,
                                icon: 'none',
                                duration: 2000
                              })
                            } else {
                              wx.showToast({
                                title: '删除失败',
                                mask: true,
                                icon: 'none',
                                duration: 2000
                              })
                            }
                          })
                        } else {
                          wx.hideLoading()
                          wx.showToast({
                            title: '删除失败',
                            mask: true,
                            icon: 'none',
                            duration: 2000
                          })
                          var datacom = {
                            code: "zg/bleSendVoucherReply",
                            data: {
                              lockerId: deviceinfo.deviceNum,
                              serialNumber: serialNumber,
                              index: FPindex,
                              type: 12,
                              result: 0
                            }
                          }
                          WXAPI.sendCommand(datacom).then(res2 => {
                            console.log(res2, '失败')
                          })
                        }
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '删除失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                      var datacom = {
                        code: "zg/bleSendVoucherReply",
                        data: {
                          lockerId: deviceinfo.deviceNum,
                          serialNumber: serialNumber,
                          index: FPindex,
                          type: 12,
                          result: 0
                        }
                      }
                      WXAPI.sendCommand(datacom).then(res2 => {
                        console.log(res2, '失败')
                      })
                    }
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '删除失败',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                  var datacom = {
                    code: "zg/bleSendVoucherReply",
                    data: {
                      lockerId: deviceinfo.deviceNum,
                      serialNumber: serialNumber,
                      index: FPindex,
                      type: 12,
                      result: 0
                    }
                  }
                  WXAPI.sendCommand(datacom).then(res2 => {
                    console.log(res2, '失败')
                  })
                }
              })
          } else {
            wx.showToast({
              title: res.msg,
              mask: true,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '删除失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  delNfcLwj(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var personLi = this.data.NfcList[index]
    passwordLiAll = personLi
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(personLi.content)
    var personInfo = JSON.parse(this.data.personLi.info)
    var _this = this
    this.getNFCIndexLwj(index, function (data) {
      if (data.length > 0) {
        let passwordIndex = JSON.parse(data[0].content).index || ''
        var dataPasswod = {
          code: "lwj/cardOperate",
          data: {
            lockerId: deviceinfo.deviceNum,
            lockerUserId: personInfo.userId,
            startTime: personLi.startTime,
            endTime: personLi.endTime,
            order: 6212,
            operateMode: 12,
            action: 2,
            // cardNo: info.password,
            passwordIndex: passwordIndex,
            type: 12,
            cardName: _this.data.personLi.name,
            roomName: deviceinfo.roomName
          }
        }
        console.log(dataPasswod, 'dataPasswod', info)
        WXAPI.sendCommand(dataPasswod).then(res => {
          console.log(res, '获取索引')
          if (res.success) {
            rfCardIndex = res.data.index
            serialNumber = res.data.serialNumber
            rfCardId = info.password
            taskId = 62
            _this.initBluetooth()
          } else {
            wx.hideLoading()
            wx.showToast({
              title: res.msg,
              mask: true,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '删除失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  delFp1(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var cgInfo = this.data.cgInfo
    var personLi = this.data.FpList[index]
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(personLi.content)
    var person = this.data.personLi
    var _this = this
    this.getFpIndex(index, function (data) {
      if (data.length > 0) {
        var FPindex = data[0].face
        var timestamp = moment().format("x")
        var fingerprintId = ''
        if (Number(FPindex) < 9) {
          fingerprintId = '0' + FPindex.toString(16)
        } else {
          fingerprintId = FPindex.toString(16)
        }
        var data1 = {
          managerTelephone: "18270949468",
          managerPassword: '202108',
          userTelephone: info.userTelephone,
          userPassword: info.userPassword,
          password: fingerprintId,
          startTime: "20210813010101",
          endTime: "20680813010101"
        }
        bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone,
          data1.userPassword, data1.password, data1.startTime, data1.endTime, 18, timestamp,
          function (res) {
            if (res.success) {
              var dataPasswod = {
                code: "ble/operateUserInfo",
                data: {
                  deviceNum: deviceinfo.deviceNum,
                  imei: deviceinfo.imei,
                  userTelephone: info.userTelephone,
                  userPassword: info.userPassword,
                  password: fingerprintId,
                  userStartTime: info.passwordStartTime,
                  userEndTime: info.passwordEndTime,
                  passwordStartTime: info.passwordStartTime,
                  passwordEndTime: info.passwordEndTime,
                  operateMode: 18,
                  order: 6218,
                  timestamp: timestamp,
                  managerTelephone: '18270949468',
                  managerPassword: '202108',
                  passwordLength: 10,
                  permission: 4294967295,
                  times: 255,
                  recycleTime: "65535",
                  roomName: _this.data.deviceinfo.roomName,
                  cardName: _this.data.personLi.name,
                }
              }
              var data = {
                ids: [personLi.id]
              }
              wx.hideLoading()
              WXAPI.deleteCertificates(data).then(res1 => {
                if (res1.success) {
                  _this.getFp()
                  wx.showToast({
                    title: '删除成功',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: '删除失败',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
              WXAPI.sendCommand(dataPasswod).then(res1 => {
                console.log(res1, '获取索引')
                if (res1.success) {
                  var data4 = {
                    result: 1,
                    serial: res1.data.serialNumber
                  }
                  WXAPI.updatePush(data4).then(res4 => {

                  })
                } else {
                  wx.showToast({
                    title: res1.msg,
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.hideLoading()
            }
          })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '获取指纹ID失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  delFpLwj(index) {
    console.log("删除指纹");
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var cgInfo = this.data.cgInfo
    var personLi = this.data.FpList[index]
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(personLi.content)
    var person = this.data.personLi
    var _this = this
    this.getFpIndex(index, function (data) {
      if (data.length > 0) {
        var FPindex = data[0].face
        // 删除
        var dataFP = {
          code: "",
          data: {
            lockerId: deviceinfo.deviceNum,
            imei: deviceinfo.imei,
            lockerUserId: info.userPassword,
            keyId: info.userPassword,
            fingerType: 0,
            order: 6216,
            fingerId: '',
            roomName: deviceinfo.roomName,
            cardName: cardName,
            startTime: passwordStartTime,
            endTime: passwordEndTime,
            file: '',
            type: 1,
            action: 2
          }
        }
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '获取指纹ID失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  delFp(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var cgInfo = this.data.cgInfo
    var personLi = this.data.FpList[index]
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(personLi.content)
    var personInfo = JSON.parse(this.data.personLi.info)
    var _this = this
    this.getFpIndex(index, function (data) {
      if (data.length > 0) {
        var FPindex = data[0].face
        var dataPasswod = {
          code: "zg/fpOperate",
          data: {
            lockerId: deviceinfo.deviceNum,
            imei: deviceinfo.imei,
            lockerUserId: personInfo.userId,
            keyId: personInfo.userId,
            fingerId: FPindex,
            fingerType: '0',
            startTime: personLi.startTime,
            endTime: personLi.endTime,
            order: 6218,
            action: 2,
            type: 1,
            roomName: _this.data.deviceinfo.roomName,
            cardName: _this.data.personLi.name,
          }
        }
        WXAPI.sendCommand(dataPasswod).then(res => {
          console.log(res, '获取索引')
          if (res.success) {
            var fingerNo = FPindex.toString(16)
            if (fingerNo < 10) {
              fingerNo = '000' + fingerNo
            } else {
              fingerNo = '00' + fingerNo
            }
            ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
              (callback) => {
                console.log(callback)
                if (callback.status == '00') {
                  ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, callback.signKey, (callback1) => {
                    console.log(callback1)
                    if (callback1.status == '00') {
                      var startTime = personLi.startTime.toString(16).toUpperCase()
                      var endTime = personLi.endTime.toString(16).toUpperCase()
                      console.log(cgInfo.lockerId, cgInfo.superId, personInfo.userId, personInfo.userId, '01', fingerNo, '', callback.signKey, '00', startTime, endTime, callback1.commonKey, '-----')
                      ICINLocker.modifyFingerPrints(cgInfo.lockerId, cgInfo.superId, personInfo.userId, personInfo.userId, '01', fingerNo, '', callback.signKey, '00', startTime, endTime, callback1.commonKey, (
                        callback2) => {
                        console.log(callback2)
                        if (callback2.status == '00') {
                          var datacom = {
                            code: "zg/bleSendVoucherReply",
                            data: {
                              lockerId: deviceinfo.deviceNum,
                              serialNumber: res.data.serialNumber,
                              index: FPindex,
                              type: 18,
                              result: 1
                            }
                          }
                          WXAPI.sendCommand(datacom).then(res2 => {
                            console.log(res2, '成功----')
                          })
                          wx.showToast({
                            title: '下发成功',
                            mask: true,
                            icon: 'none',
                            duration: 2000
                          })
                          var data = {
                            ids: [personLi.id]
                          }
                          wx.hideLoading()
                          WXAPI.deleteCertificates(data).then(res1 => {
                            if (res1.success) {
                              _this.getFp()
                              wx.showToast({
                                title: '删除成功',
                                mask: true,
                                icon: 'none',
                                duration: 2000
                              })
                            } else {
                              wx.showToast({
                                title: '删除失败',
                                mask: true,
                                icon: 'none',
                                duration: 2000
                              })
                            }
                          })
                        } else {
                          wx.hideLoading()
                          wx.showToast({
                            title: '删除失败',
                            mask: true,
                            icon: 'none',
                            duration: 2000
                          })
                          var datacom = {
                            code: "zg/bleSendVoucherReply",
                            data: {
                              lockerId: deviceinfo.deviceNum,
                              serialNumber: res.data.serialNumber,
                              index: FPindex,
                              type: 18,
                              result: 0
                            }
                          }
                          WXAPI.sendCommand(datacom).then(res2 => {
                            console.log(res2, '失败')
                          })
                        }
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '删除失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                      var datacom = {
                        code: "zg/bleSendVoucherReply",
                        data: {
                          lockerId: deviceinfo.deviceNum,
                          serialNumber: res.data.serialNumber,
                          index: FPindex,
                          type: 18,
                          result: 0
                        }
                      }
                      WXAPI.sendCommand(datacom).then(res2 => {
                        console.log(res2, '失败')
                      })
                    }
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '删除失败',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                  var datacom = {
                    code: "zg/bleSendVoucherReply",
                    data: {
                      lockerId: deviceinfo.deviceNum,
                      serialNumber: res.data.serialNumber,
                      index: FPindex,
                      type: 18,
                      result: 0
                    }
                  }
                  WXAPI.sendCommand(datacom).then(res2 => {
                    console.log(res2, '失败')
                  })
                }
              })
          } else {
            var datacom = {
              code: "zg/bleSendVoucherReply",
              data: {
                lockerId: deviceinfo.deviceNum,
                serialNumber: res.data.serialNumber,
                index: FPindex,
                type: 18,
                result: 0
              }
            }
            WXAPI.sendCommand(datacom).then(res2 => {
              console.log(res2, '失败')
            })
            var data = {
              ids: [personLi.id]
            }
            wx.hideLoading()
            WXAPI.deleteCertificates(data).then(res1 => {
              if (res1.success) {
                _this.getFp()
              }
            })
            wx.hideLoading()
            wx.showToast({
              title: res.msg,
              mask: true,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '获取失败',
          mask: true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  delPassword1(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var passwordLi = this.data.passwordList[index]
    passwordLiAll = passwordLi
    var info = JSON.parse(passwordLi.content)
    var data = {
      managerTelephone: "18270949468",
      managerPassword: "202108",
      userTelephone: info.userTelephone,
      userPassword: info.userPassword,
      password: info.password,
      startTime: info.passwordStartTime,
      endTime: info.passwordEndTime
    }
    console.log(data)
    var timestamp = moment().format("x")
    bleall.startFp1_63(data.managerTelephone, data.managerPassword, data.userTelephone,
      data.userPassword, data.password, data.startTime, data.endTime, 9, timestamp,
      function (res) {
        if (res.success) {
          var data = {
            ids: [passwordLi.id]
          }
          WXAPI.deleteCertificates(data).then(res1 => {
            if (res1.success) {
              var data3 = {
                code: "ble/operateUserInfo",
                data: {
                  deviceNum: deviceinfo.deviceNum,
                  imei: deviceinfo.imei,
                  userTelephone: info.userTelephone,
                  userPassword: info.userPassword,
                  password: info.password,
                  userStartTime: info.passwordStartTime,
                  userEndTime: info.passwordEndTime,
                  passwordStartTime: info.passwordStartTime,
                  passwordEndTime: info.passwordEndTime,
                  operateMode: 9,
                  order: 6209,
                  timestamp: timestamp,
                  managerTelephone: '18270949468',
                  managerPassword: '202108',
                  passwordLength: 10,
                  permission: 4294967295,
                  times: 255,
                  recycleTime: "65535",
                  roomName: _this.data.deviceinfo.roomName,
                  cardName: _this.data.personLi.name,
                }
              }
              WXAPI.sendCommand(data3).then(res => {
                if (res.success) {
                  var data4 = {
                    result: 1,
                    serial: res.data.serialNumber
                  }
                  WXAPI.updatePush(data4).then(res4 => {

                  })
                }
              })
              _this.getPassword()
              wx.hideLoading()
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '删除失败',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          })
        }
        if (res.data == "蓝牙功能暂不支持") {
          // wx.hideLoading()
          // wx.showLoading({
          //   title: '重新连接蓝牙中'
          // })
          _this.startconnect()
        }
      })
  },
  startconnect() {
    wx.showLoading({
      title: "连接蓝牙中",
      mask: true
    })
    this.setData({
      showLoading: true
    })
    // this.setData({
    //   showLoading: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
    if (app.globalData.ble) {
      app.globalData.ble.listen(res => {
        if (res.type == 'connect') {
          if (res.data == "未打开适配器") {
            this.setData({
              showLoading: false
            })
            wx.hideLoading()
            wx.showModal({
              title: "提示",
              content: "请检查手机蓝牙和定位功能是否打开？",
              showCancel: false,
              confirmText: "确定",
              success(res) {}
            });
          } else {
            if (res.data == '蓝牙已连接') {
              app.globalData.bleStatus = res.data
              this.setData({
                showLoading: false
              })
              if (this.data.current == 0) {
                this.sendPassword()
              } else if (that.data.current == 1) {
                this.delPassword1(this.data.currentIndex)
              } else if (that.data.current == 2) {
                this.sendFp()
              }
            }
          }
        }
      })
    }
  },
  delPasswordLwj(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var passwordLi = this.data.passwordList[index]
    passwordLiAll = passwordLi
    var info = JSON.parse(passwordLi.content)
    var personInfo = JSON.parse(this.data.personLi.info)
    var cgInfo = this.data.cgInfo
    var dataPasswod = {
      code: "lwj/passwordOperate",
      data: {
        lockerId: deviceinfo.deviceNum,
        lockerUserId: personInfo.userId,
        startTime: passwordLi.startTime,
        endTime: passwordLi.endTime,
        order: 6209,
        operateMode: 9,
        action: 2,
        password: info.password,
        type: 9,
        cardName: _this.data.personLi.name,
        roomName: deviceinfo.roomName
      }
    }
    console.log(dataPasswod, 'dataPasswod', info)
    WXAPI.sendCommand(dataPasswod).then(res => {
      console.log(res, '获取索引')
      if (res.success) {
        pincodeIndex = res.data.index
        serialNumber = res.data.serialNumber
        taskId = 52
        _this.initBluetooth()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          mask: true,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  onDelRfCard: function () {
    var that = this
    wx.showLoading({
      title: '删除房卡中',
    })
    var bytes = plugin.delRfCard(lockDevice.name, basecode, 0, rfCardIndex)
    console.debug('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)
  },
  delPassword(index) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var passwordLi = this.data.passwordList[index]
    passwordLiAll = passwordLi
    var info = JSON.parse(passwordLi.content)
    var personInfo = JSON.parse(this.data.personLi.info)
    var cgInfo = this.data.cgInfo
    var dataPasswod = {
      code: "zg/tempPassword",
      data: {
        lockerId: deviceinfo.deviceNum,
        imei: deviceinfo.imei,
        passwordCount: 255,
        lockerUserId: personInfo.userId,
        keyId: personInfo.userId,
        passwordStartTime: passwordLi.startTime,
        passwordEndTime: passwordLi.endTime,
        order: 6209,
        action: 2,
        password: info.password,
        type: 1,
        cardName: _this.data.personLi.name,
        roomName: deviceinfo.roomName
      }
    }
    console.log(dataPasswod, 'dataPasswod', info)
    WXAPI.sendCommand(dataPasswod).then(res => {
      console.log(res, '获取索引')
      if (res.success) {
        var pwdNo = res.data.index.toString(16)
        var passwordIndex = res.data.index
        if (pwdNo < 9) {
          pwdNo = '0' + pwdNo
        } else {
          pwdNo = pwdNo
        }
        ICINLocker.getUserSignKey(cgInfo.lockerId, cgInfo.superId, personInfo.userId, cgInfo.superId, cgInfo.authKey, '01', (callback) => {
          console.log(callback)
          if (callback.status == '00') {
            var userSignKey = callback.userSignKey
            ICINLocker.getCommonKey(cgInfo.lockerId, personInfo.userId, personInfo.userId, userSignKey, (callback) => {
              if (callback.status == '00') {
                console.log(callback, 'commonKey')
                var commonKey = callback.commonKey
                var startTime = passwordLi.startTime.toString(16).toUpperCase()
                var endTime = passwordLi.endTime.toString(16).toUpperCase()
                ICINLocker.handlePwd(deviceinfo.deviceNum, cgInfo.superId, personInfo.userId, info.password, pwdNo, cgInfo.superId, cgInfo.authKey, '', startTime, endTime, 0, commonKey, (callback) => {
                  console.log(callback)
                  if (callback.status == '00') {
                    var datacom = {
                      code: "zg/bleSendVoucherReply",
                      data: {
                        lockerId: deviceinfo.deviceNum,
                        serialNumber: res.data.serialNumber,
                        index: passwordIndex,
                        type: 9,
                        result: 1
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {
                      if (res2.success) {}
                    })
                    var data = {
                      ids: [passwordLiAll.id]
                    }
                    WXAPI.deleteCertificates(data).then(res1 => {
                      if (res1.success) {
                        _this.getPassword()
                        wx.hideLoading()
                        wx.showToast({
                          title: '删除成功',
                          mask: true,
                          icon: 'none',
                          duration: 2000
                        })
                      } else {
                        wx.hideLoading()
                        wx.showToast({
                          title: '删除失败',
                          mask: true,
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '删除失败',
                      mask: true,
                      icon: 'none',
                      duration: 2000
                    })
                    var datacom = {
                      code: "zg/bleSendVoucherReply",
                      data: {
                        lockerId: deviceinfo.deviceNum,
                        serialNumber: res.data.serialNumber,
                        index: res.data.index,
                        type: 9,
                        result: 0
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {
                      console.log(res2, '失败')
                    })
                  }
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '删除失败',
                  mask: true,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '删除失败',
              mask: true,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          mask: true,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  getPassWordMehods(content, id, type) {
    var that = this
    var data = {
      pageNum: 0,
      pageSize: 0,
      orderBy: "create_at desc",
      q: {
        cardId: id,
        password: content,
        deviceNum: this.data.deviceinfo.deviceNum,
        types: type,
        inStatus: '0,1,702'
      },
    };
    WXAPI.getCertificates(data).then(res => {
      if (res.success) {
        var dataOne = util.zlib_unzip(res.data)
        if (dataOne.length > 0) {
          wx.showModal({
            title: '提示',
            content: '该密码已存在，不能重复添加',
            success(res1) {
              if (res1.confirm) {
                console.log('用户点击确定')
                that.setData({
                  password: '',
                  passwordStatus: false
                })
              } else if (res1.cancel) {
                console.log('用户点击取消')
                that.setData({
                  password: '',
                  passwordStatus: false
                })
              }
            }
          })
        } else {
          this.setData({
            passwordStatus: true
          })
        }
      } else {
        wx.showToast({
          title: '获取失败',
          duration: '2000',
          mask: true,
          icon: 'none'
        })
      }
    })
  },
  sendPassword() {
    let passwordLength = this.data.password.toString()
    if (passwordLength.length != 6) {
      wx.showToast({
        title: '格式错误，密码为6位数字！',
        icon: 'none'
      })
      return false;
    }
    wx.showLoading({
      title: '正在添加',
      mask: true,
    })
    var time3 = new Date(this.data.datetimerange[0].replace(/-/g, '/'))
    var time4 = new Date(this.data.datetimerange[1].replace(/-/g, '/'))
    var passwordStartTimecontrast = time3.getTime() / 1000
    var passwordEndTimecontrast = time4.getTime() / 1000
    this.getPassWordMehods(this.data.password, this.data.personLi.cardId, 14)
    if (this.data.password == '') {
      wx.showToast({
        title: '密码不能为空',
        mask: true,
        duration: 2000,
        icon: 'none'
      })
      return
    }
    if (!this.data.passwordStatus) {
      wx.showToast({
        title: '已存在该密码，请重输',
        duration: 2000,
        mask: true,
        icon: 'none'
      })
      return
    }
    if (passwordStartTimecontrast > passwordEndTimecontrast) {
      wx.showToast({
        title: '开始时间不能大于结束时间',
        duration: 2000,
        mask: true,
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '正在添加',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(this.data.personLi.info)
    if (deviceinfo.manufactureId == 101) {
      var time1 = moment(this.data.datetimerange[0]).format("YYYYMMDDHHmmss")
      var time2 = moment(this.data.datetimerange[1]).format("YYYYMMDDHHmmss")
      var time3 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
      var time4 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
      var passwordStartTime = time3.getTime() / 1000
      var passwordEndTime = time4.getTime() / 1000
      var data1 = {
        managerTelephone: "18270949468",
        managerPassword: '202108',
        userTelephone: info.userTelephone,
        userPassword: info.userPassword,
        password: this.data.password,
        startTime: time1,
        endTime: time2
      }
      var timestamp = moment().format("x")
      bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone,
        data1.userPassword, data1.password, data1.startTime, data1.endTime, 7, timestamp,
        function (res) {
          console.log(res)
          if (res.success) {
            var pzname = '',
              cardName = ''
            pzname = '蓝牙-密码' + (_this.data.passwordList.length + 1)
            cardName = _this.data.personLi.name + '-蓝牙-密码' + (_this.data.passwordList.length + 1)
            var str = {
              // cardId: this.personInfo.cardId,
              pzname: pzname,
              imei: _this.data.deviceinfo.imei,
              password: _this.data.password.toString(),
              userTelephone: JSON.parse(_this.data.personLi.info).userTelephone,
              operateMode: 7,
              userPassword: JSON.parse(_this.data.personLi.info).userPassword,
              passwordStartTime: time1,
              passwordEndTime: time2,
              is: false,
              pass: true
            }
            var data3 = {
              code: "ble/operateUserInfo",
              data: {
                deviceNum: _this.data.deviceinfo.deviceNum,
                imei: _this.data.deviceinfo.imei,
                userTelephone: info.userTelephone,
                userPassword: info.userPassword,
                password: _this.data.password,
                userStartTime: time1,
                userEndTime: time2,
                passwordStartTime: time1,
                passwordEndTime: time2,
                operateMode: 7,
                order: 6207,
                timestamp: timestamp,
                managerTelephone: '18270949468',
                managerPassword: '202108',
                passwordLength: 10,
                permission: 4294967295,
                times: 255,
                recycleTime: "65535",
                roomName: _this.data.deviceinfo.roomName,
                cardName: cardName,
              }
            }
            WXAPI.sendCommand(data3).then(res3 => {
              if (res3.success) {
                var data4 = {
                  result: 1,
                  serial: res3.data.serialNumber
                }
                WXAPI.updatePush(data4).then(res4 => {

                })
                var data = {
                  cardId: _this.data.personLi.cardId,
                  content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                  deviceNum: _this.data.deviceinfo.deviceNum,
                  type: 4,
                  imei: _this.data.deviceinfo.imei,
                  serial: res3.data.serialNumber,
                  startTime: passwordStartTime,
                  endTime: passwordEndTime,
                };
                var datalist = {
                  cardId: _this.data.personLi.cardId,
                  content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                  type: 14,
                  startTime: passwordStartTime,
                  endTime: passwordEndTime,
                };
                console.log(datalist, '密码11')
                WXAPI.addCertificates(datalist).then(res6 => {
                  console.log(datalist, '密码22')
                })
                WXAPI.addCertificates(data).then(res3 => {
                  if (res3.success) {
                    var updatedata = {
                      id: res3.data,
                      status: 1
                    };
                    WXAPI.updateCertificates(updatedata).then((res2) => {});
                    _this.getPassword()
                    _this.setData({
                      show: false
                    })
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加成功',
                      icon: 'none',
                      mask: true,
                      duration: 2000
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加失败',
                      mask: true,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: res3.msg,
                  mask: true,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            wx.hideLoading()
            if (res.data == "蓝牙功能暂不支持") {
              // wx.showToast({
              //   title: '重新连接蓝牙中',
              //   duration: 2000,
              //   icon: "none"
              // })
              _this.startconnect()
            } else {
              wx.showToast({
                title: '下发失败',
                mask: true,
                duration: 2000,
                icon: "none"
              })
            }
          }
        })
    } else if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      var cgInfo = this.data.cgInfo
      var time1 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
      var time2 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
      var passwordStartTime = time1.getTime() / 1000
      var passwordEndTime = time2.getTime() / 1000
      var pzname = '',
        cardName = ''
      pzname = '蓝牙-密码' + (_this.data.passwordList.length + 1)
      cardName = _this.data.personLi.name + '-蓝牙-密码' + (_this.data.passwordList.length + 1)
      var dataPasswod = {
        code: "zg/tempPassword",
        data: {
          lockerId: deviceinfo.deviceNum,
          imei: deviceinfo.imei,
          passwordCount: 255,
          lockerUserId: info.userId,
          keyId: info.userId,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          order: 6207,
          action: 1,
          password: this.data.password.toString(),
          type: 1,
          roomName: this.data.deviceinfo.roomName,
          cardName: cardName,
        }
      }
      WXAPI.sendCommand(dataPasswod).then(res => {
        console.log(res, '获取索引')
        if (res.success) {
          var pwdNo = res.data.index
          var passwordIndex = res.data.index
          // var str = res.data.index
          pwdNo = pwdNo.toString(16)
          if (pwdNo.length < 2) {
            pwdNo = '0' + pwdNo
          }
          var startTime = passwordStartTime.toString(16).toUpperCase()
          var endTime = passwordEndTime.toString(16).toUpperCase()
          info.startTime = startTime
          info.endTime = endTime
          info.pwdNo = pwdNo
          info.password = this.data.password.toString()
          methods.bluetoothOperation_ZH(cgInfo, info, 3).then(result => {
            if (result.status == '00' || result.status == '0a') {
              var datacom = {
                code: "zg/bleSendVoucherReply",
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: res.data.serialNumber,
                  index: passwordIndex,
                  type: 7,
                  result: 1
                }
              }
              var str = {
                // cardId: this.personInfo.cardId,
                imei: _this.data.deviceinfo.imei,
                pzname: pzname,
                password: _this.data.password.toString(),
                userTelephone: JSON.parse(_this.data.personLi.info).userTelephone,
                operateMode: 7,
                userPassword: JSON.parse(_this.data.personLi.info).userPassword,
                passwordStartTime: passwordStartTime,
                passwordEndTime: passwordEndTime,
                is: false,
                pass: true
              }
              var data = {
                cardId: _this.data.personLi.cardId,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                deviceNum: _this.data.deviceinfo.deviceNum,
                type: 4,
                imei: _this.data.deviceinfo.imei,
                serial: res.data.serialNumber,
                startTime: passwordStartTime,
                endTime: passwordEndTime,
              };
              var datalist = {
                cardId: _this.data.personLi.cardId,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: 14,
                startTime: passwordStartTime,
                endTime: passwordEndTime,
              };
              console.log(datalist, '密码11')
              WXAPI.addCertificates(datalist).then(res6 => {
                console.log(datalist, '密码22', res6)
              })
              console.log(data, '添加凭证')
              WXAPI.addCertificates(data).then(res3 => {
                if (res3.success) {
                  var updatedata = {
                    id: res3.data,
                    status: 1
                  };
                  WXAPI.updateCertificates(updatedata).then((res2) => {});
                  WXAPI.sendCommand(datacom).then(res2 => {
                    if (res2.success) {}
                  })
                  console.log(res3, '添加凭证成功')
                  _this.getPassword()
                  _this.setData({
                    show: false
                  })
                  wx.hideLoading()
                  wx.showToast({
                    title: '添加成功',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '添加失败',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.showToast({
                title: '添加失败',
                mask: true,
                icon: 'none',
                duration: 2000
              })
              var datacom = {
                code: "zg/bleSendVoucherReply",
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: res.data.serialNumber,
                  index: res.data.index,
                  type: 7,
                  result: 0
                }
              }
              WXAPI.sendCommand(datacom).then(res2 => {
                console.log(res2, '失败')
                _this.setData({
                  show: false
                })
              })
            }
          }).catch(err => {
            wx.hideLoading()
            wx.showToast({
              title: '添加失败',
              icon: 'none',
              mask: true,
              duration: 2000
            })
            var datacom = {
              code: "zg/bleSendVoucherReply",
              data: {
                lockerId: deviceinfo.deviceNum,
                serialNumber: res.data.serialNumber,
                index: res.data.index,
                type: 7,
                result: 0
              }
            }
            WXAPI.sendCommand(datacom).then(res2 => {
              console.log(res2, '失败')
              _this.setData({
                show: false
              })
            })
          })
        } else {
          wx.showToast({
            title: res.msg,
            duration: 2000,
            mask: true,
            icon: 'none'
          })
        }
      })
    } else if (deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241) {
      console.log(this.data.isSearch);
      if (this.data.isSearch) {
        wx.hideLoading()
        this.addPincode()
      } else {
        this.searchDevicesMethods()
      }
    }
  },
  onAddPincode: function () {
    console.log("2073123");
    var that = this
    wx.showLoading({
      title: '添加密码中',
    })
    var info = JSON.parse(this.data.personLi.info)
    let deviceinfo = this.data.deviceinfo
    var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
    var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
    var passwordStartTime = time1.getTime() / 1000
    var passwordEndTime = time2.getTime() / 1000
    var pzname = '',
      cardName = ''
    pzname = '蓝牙-密码' + (that.data.passwordList.length + 1)
    cardName = that.data.personLi.name + '-蓝牙-密码' + (that.data.passwordList.length + 1)
    var dataPasswod = {
      code: "lwj/passwordOperate",
      data: {
        lockerId: deviceinfo.deviceNum,
        lockerUserId: info.userId,
        startTime: passwordStartTime,
        endTime: passwordEndTime,
        order: 6207,
        operateMode: 7,
        action: 1,
        password: this.data.password.toString(),
        type: 7,
        roomName: this.data.deviceinfo.roomName,
        cardName: cardName,
      }
    }
    WXAPI.sendCommand(dataPasswod).then(res => {
      console.log(res, '获取索引')
      if (res.success) {
        var pwdNo = res.data.index
        serialNumber = res.data.serialNumber
        pincodeIndex = pwdNo
        that.sendAddPincode()
      }
    })
    // var startTime = util1.getLocalTime(8)
    // var endTime = new Date(startTime.getTime() + 5 * 60 * 1000) //有效期5分钟
  },
  sendAddPincode() {
    var that = this
    var startTime = new Date(Number(moment(that.data.starttime).format('x')))
    var endTime = new Date(Number(moment(that.data.endtime).format('x')))
    pincode = this.data.password
    console.log(lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime)
    let bytes = plugin.addPincode(lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime)
    console.log('bytes', bytes)
    that.sendBytes(bytes)
  },
  addPincode: function () {
    console.log("2124");
    var that = this
    taskId = 51
    that.initBluetooth()
  },
  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 == that.data.deviceinfo.deviceNum) {
            isConnected = true
          }
        })
        that.setData({
          isConnected: isConnected
        })
        console.log(isInitReady, 'isConnected', isConnected)
        if (isConnected) {
          console.log("2144");
          if (isInitReady) {
            console.log("2146");
            that.doWork()
          } else {
            that.setupConnection()
          }
        } else {
          that.connectTo()
        }
      },
    })
  },
  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.showToast({
              title: '连接成功',
              duration: 1000,
              icon: 'none'
            })
            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) {
                          console.log(data.data, 'rfCardIdrfCardId')
                          // rfCardId = randomMethods()//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) {
                    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: "zg/bleUnlockRecord",
                    //   data: {
                    //     lockerId: that.data.deviceinfo.deviceNum,
                    //     roomId:that.data.deviceinfo.roomId,
                    //     roomName:that.data.deviceinfo.roomName,
                    //     cardName:that.data.userInfo.username
                    //   }
                    // }
                    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': {
                  // console.log(data.data,'data.data')
                  // wx.hideLoading()
                  let data2 = {
                    "code": "ble/bleSendVoucherReply",
                    "data": {
                      "deviceNum": that.data.deviceinfo.deviceNum,
                      "serialNumber": serialNumber,
                      "index": pincodeIndex,
                      "type": 7,
                      "result": 1,
                      "productId": that.data.deviceinfo.manufactureId
                    }
                  }
                  if (data.code != 200) {
                    data2 = {
                      "code": "ble/bleSendVoucherReply",
                      "data": {
                        "deviceNum": that.data.deviceinfo.deviceNum,
                        "serialNumber": serialNumber,
                        "index": pincodeIndex,
                        "type": 7,
                        "result": 0,
                        "productId": that.data.deviceinfo.manufactureId
                      }
                    }
                    WXAPI.sendCommand(data2).then(res => {

                    })
                    wx.showModal({
                      title: '提示',
                      content: '添加密码失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
                  var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
                  var passwordStartTime = time1.getTime() / 1000
                  var passwordEndTime = time2.getTime() / 1000
                  var pzname = '',
                    cardName = '';
                  pzname = '蓝牙-密码' + (that.data.passwordList.length + 1)
                  cardName = that.data.personLi.name + '-蓝牙-密码' + (that.data.passwordList.length + 1)
                  var str = {
                    // cardId: this.personInfo.cardId,
                    imei: that.data.deviceinfo.imei,
                    pzname: pzname,
                    password: that.data.password.toString(),
                    userTelephone: JSON.parse(that.data.personLi.info).userTelephone,
                    operateMode: 7,
                    userPassword: JSON.parse(that.data.personLi.info).userPassword,
                    passwordStartTime: passwordStartTime,
                    passwordEndTime: passwordEndTime,
                    index: pincodeIndex,
                    is: false,
                    pass: true
                  }
                  var data1 = {
                    cardId: that.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    deviceNum: that.data.deviceinfo.deviceNum,
                    type: 4,
                    imei: that.data.deviceinfo.imei,
                    serial: serialNumber,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  var datalist = {
                    cardId: that.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 14,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  WXAPI.addCertificates(datalist).then(res6 => {
                    console.log(datalist, '密码22', res6)
                  })
                  WXAPI.addCertificates(data1).then(res3 => {
                    if (res3.success) {
                      var updatedata = {
                        id: res3.data,
                        status: 1
                      };
                      WXAPI.updateCertificates(updatedata).then((res2) => {});
                      WXAPI.sendCommand(data2).then(res => {

                      })
                      that.getPassword()
                      that.setData({
                        show: false
                      })
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加成功',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                  taskId = 0
                  that.setData({
                    isPincodeAdd: true,
                    show: false
                  })
                  wx.showModal({
                    title: '提示',
                    content: `添加密码${pincode}成功！`,
                    showCancel: false
                  })
                  break
                }

                case 'delPincode': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    var datacom = {
                      code: "lwj/passwordOperate",
                      data: {
                        lockerId: that.data.deviceinfo.deviceNum,
                        serialNumber: serialNumber,
                        index: pincodeIndex,
                        action: 2,
                        type: 9,
                        result: 0
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {
                      console.log(res2, '失败')
                    })

                    wx.showModal({
                      title: '提示',
                      content: '删除密码失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: `删除密码成功！`,
                    showCancel: false,
                  })
                  var datacom = {
                    code: "lwj/passwordOperate",
                    data: {
                      lockerId: that.data.deviceinfo.deviceNum,
                      serialNumber: serialNumber,
                      index: pincodeIndex,
                      action: 2,
                      type: 9,
                      result: 1
                    }
                  }
                  WXAPI.sendCommand(datacom).then(res2 => {
                    if (res2.success) {}
                  })
                  var data = {
                    ids: [passwordLiAll.id]
                  }
                  WXAPI.deleteCertificates(data).then(res1 => {
                    if (res1.success) {
                      that.getPassword()
                      wx.hideLoading()
                      wx.showToast({
                        title: '删除成功',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '删除失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                  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) {
                    var datacom = {
                      code: "ble/bleSendVoucherReply",
                      data: {
                        deviceNum: that.data.deviceinfo.deviceNum,
                        serialNumber: serialNumber,
                        index: rfCardIndex,
                        type: ADD_NFC_MODE,
                        cardNo: '',
                        result: 0,
                        productId: that.data.deviceinfo.manufactureId
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {})
                    wx.showModal({
                      title: '提示',
                      content: '添加房卡失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  taskId = 0
                  that.setData({
                    isRfCardAdd: true
                  })

                  if (lockModel > 70) {
                    console.log(data.data, 'rfCardIndexrfCardIndex')
                    // rfCardId = randomMethods()
                    wx.showModal({
                      title: '提示',
                      content: `添加房卡成功，序号${rfCardIndex}！`,
                      showCancel: false
                    })
                    that.addRfcardCertificates()
                  } else {
                    console.log(data.data, 'rfCardIndexrfCardIndex1')
                    // rfCardId = randomMethods()
                    wx.showModal({
                      title: '提示',
                      content: `添加房卡成功，卡号${rfCardId}！`,
                      showCancel: false
                    })
                    that.addRfcardCertificates()
                  }
                  break
                }

                case 'delRfCard': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    var datacom = {
                      code: "lwj/c",
                      data: {
                        lockerId: that.data.deviceinfo.deviceNum,
                        serialNumber: serialNumber,
                        index: rfCardIndex,
                        action: 2,
                        type: 12,
                        result: 0
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {
                      console.log(res2, '失败')
                    })
                    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,
                    })
                  }
                  var datacom = {
                    code: "lwj/c",
                    data: {
                      lockerId: that.data.deviceinfo.deviceNum,
                      serialNumber: serialNumber,
                      index: rfCardIndex,
                      action: 2,
                      type: 12,
                      result: 1
                    }
                  }
                  WXAPI.sendCommand(datacom).then(res2 => {
                    console.log(res2, '失败')
                  })
                  var data = {
                    ids: [passwordLiAll.id]
                  }
                  WXAPI.deleteCertificates(data).then(res1 => {
                    console.log(res1, '2936');
                    if (res1.success) {
                      that.getNfc()
                      wx.showToast({
                        title: '删除成功',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      wx.showToast({
                        title: '删除失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                  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) {}
                    })
                    var datacom = {
                      code: "ble/bleSendVoucherReply",
                      data: {
                        deviceNum: that.data.deviceinfo.deviceNum,
                        serialNumber: serialNumber,
                        index: 0,
                        type: 16,
                        result: 0,
                        productId: that.data.deviceinfo.manufactureId
                      }
                    }
                    WXAPI.sendCommand(datacom).then(res2 => {
                      if (res2.success) {}
                    })
                    break
                  }
                  taskId = 0
                  that.setData({
                    isFingerprintAdd: true
                  })
                  wx.showModal({
                    title: '提示',
                    content: `添加指纹成功，序号${fingerprintIndex}！`,
                    showCancel: false
                  })

                  var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
                  var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
                  var passwordStartTime = time1.getTime() / 1000
                  var passwordEndTime = time2.getTime() / 1000
                  var cardName = '',
                    pzname = ''
                  if (that.data.pzname) {
                    cardName = that.data.personLi.name + '-蓝牙-' + that.data.pzname
                    pzname = '蓝牙-' + that.data.pzname
                  } else {
                    cardName = that.data.personLi.name + '-蓝牙-指纹' + (that.data.FpList.length + 1)
                    pzname = '蓝牙-指纹' + (that.data.FpList.length + 1)
                  }

                  var str = {
                    // cardId: this.personInfo.cardId,
                    imei: that.data.deviceinfo.imei,
                    pzname: pzname,
                    password: '',
                    fingerprintAlias: that.data.radioDetil,
                    userTelephone: JSON.parse(that.data.personLi.info).userTelephone,
                    operateMode: 16,
                    userPassword: JSON.parse(that.data.personLi.info).userPassword,
                    passwordStartTime: passwordStartTime,
                    passwordEndTime: passwordEndTime,
                    index: fingerprintIndex,
                    is: false,
                    pass: true
                  }
                  var data2 = {
                    cardId: that.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    deviceNum: that.data.deviceinfo.deviceNum,
                    type: 1,
                    imei: that.data.deviceinfo.imei,
                    serial: serialNumber,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                    status: 1
                  };
                  var datalist = {
                    cardId: that.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 11,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime
                  };
                  var datacom = {
                    code: "ble/bleSendVoucherReply",
                    data: {
                      deviceNum: that.data.deviceinfo.deviceNum,
                      serialNumber: serialNumber,
                      index: fingerprintIndex,
                      type: 16,
                      result: 1,
                      productId: that.data.deviceinfo.manufactureId
                    }
                  }
                  WXAPI.addCertificates(datalist).then(res6 => {})
                  console.log(data, '添加凭证')
                  WXAPI.addCertificates(data2).then(res3 => {
                    if (res3.success) {
                      var updatedata = {
                        id: res3.data,
                        status: 1
                      };
                      WXAPI.updateCertificates(updatedata).then((res2) => {});
                      WXAPI.sendCommand(datacom).then(res2 => {
                        if (res2.success) {}
                      })
                      console.log(res3, '添加凭证成功')
                      that.getFp()
                      that.setData({
                        show: false
                      })
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加成功',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                  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()
                  that.login()
                }, 500)
              },
            })
          },
        })
      },
    })
  },
  onQueryBindState: function () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

    var bytes = plugin.queryLockState(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },
  queryBindState: function () {
    var that = this
    taskId = 21
    that.initBluetooth()
  },
  doWork: function () {
    var that = this
    console.log(taskId);
    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: {
        // that.onAddRfCard()
        // if (lockModel > 70) {
        that.sendAddRfcard()
        // } 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()
      }
      default: {

      }
    }
  },
  connectTo: function () {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    wx.createBLEConnection({
      deviceId: lockDevice.deviceId,
      timeout: config.ble.connectTimeOut,
      success: function (res) {
        console.log('connectTo', res)
        isConnected = true
        // app.globalData.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
          }
        }
      }
    })
  },

  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) {
                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)
                        lockDevice = it
                        connectedDeviceId = it.deviceId
                        that.setData({
                          isSearch: true
                        })
                        that.initBluetooth()
                      }
                    }
                  }
                })
                if (!that.data.isSearch) {
                  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'
            })
          },
        })
      }
    })
  },
  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)
  },
  openLock: function () {
    var that = this
    taskId = 41
    that.initBluetooth()
  },
  sendBytes(bytes) {
    setTimeout(() => {
      wx.writeBLECharacteristicValue({
        deviceId: lockDevice.deviceId,
        serviceId: config.uuid.serviceUuid.toUpperCase(),
        characteristicId: config.uuid.writeUuid.toUpperCase(),
        value: bytes,
        success: function (res) {

        },
      })
    }, 50)
  },
  sendNfc() {
    var time3 = new Date(this.data.datetimerange[0].replace(/-/g, '/'))
    var time4 = new Date(this.data.datetimerange[1].replace(/-/g, '/'))
    var passwordStartTimecontrast = time3.getTime() / 1000
    var passwordEndTimecontrast = time4.getTime() / 1000
    if (passwordStartTimecontrast > passwordEndTimecontrast) {
      wx.showToast({
        title: '开始时间不能大于结束时间',
        duration: 2000,
        mask: true,
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '正在添加',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(this.data.personLi.info)
    if (deviceinfo.manufactureId == 101) {

    } else if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      var cgInfo = this.data.cgInfo
      var time1 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
      var time2 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
      var passwordStartTime = time1.getTime() / 1000
      var passwordEndTime = time2.getTime() / 1000
      var pzname = _this.data.pzname,
        cardName = ''
      if (pzname == "") {
        pzname = '蓝牙-NFC' + (_this.data.NfcList.length + 1)
        cardName = _this.data.personLi.name + '-蓝牙-NFC' + (_this.data.NfcList.length + 1)
      } else {
        pzname = '蓝牙-' + pzname
        cardName = _this.data.personLi.name + '-蓝牙-' + pzname
      }
      var dataPasswod = {
        code: "zg/cardOperate",
        data: {
          lockerId: deviceinfo.deviceNum,
          imei: deviceinfo.imei,
          lockerUserId: info.userId,
          keyId: info.userId,
          action: 1,
          taskStatus: 1,
          order: 6210,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          cardType: 50,
          type: ADD_NFC_MODE,
          roomName: this.data.deviceinfo.roomName,
          cardName: cardName,
        }
      }
      console.log(dataPasswod, 'dataPasswod')
      WXAPI.sendCommand(dataPasswod).then(res => {
        console.log(res, 'resres')
        if (res.success) {
          var pwdNo = res.data.index
          var passwordIndex = res.data.index
          var serialNumber = res.data.serialNumber
          pwdNo = pwdNo.toString(16)
          if (pwdNo.length < 2) {
            pwdNo = '0' + pwdNo
          }
          var startTime = passwordStartTime.toString(16).toUpperCase()
          var endTime = passwordEndTime.toString(16).toUpperCase()
          info.startTime = startTime
          info.endTime = endTime
          info.pwdNo = pwdNo
          methods.bluetoothOperation_ZH(cgInfo, info, 7).then(result => {
            if (result.status == '00') {
              let carNoId = this.processCardNumber(result.cardNo)
              var datacom = {
                code: "zg/bleSendVoucherReply",
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: serialNumber,
                  index: passwordIndex,
                  type: ADD_NFC_MODE,
                  cardNo: carNoId.toUpperCase(),
                  result: 1
                }
              }
              WXAPI.sendCommand(datacom).then(res2 => {
                if (res2.success) {
                  var str = {
                    // cardId: this.personInfo.cardId,
                    pzname: pzname,
                    imei: _this.data.deviceinfo.imei,
                    password: carNoId.toUpperCase(),
                    blueCardNo: result.cardNo,
                    userTelephone: JSON.parse(_this.data.personLi.info).userTelephone,
                    operateMode: 10,
                    userPassword: JSON.parse(_this.data.personLi.info).userPassword,
                    passwordStartTime: passwordStartTime,
                    passwordEndTime: passwordEndTime,
                    is: false,
                    roomName: _this.data.deviceinfo.roomName,
                  }
                  var data = {
                    cardId: _this.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    deviceNum: _this.data.deviceinfo.deviceNum,
                    type: 3,
                    blueCardNo: result.cardNo,
                    imei: _this.data.deviceinfo.imei,
                    serial: serialNumber,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  console.log(data, '添加凭证')

                  var datalist = {
                    cardId: _this.data.personLi.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 13,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  WXAPI.addCertificates(datalist).then(res6 => {
                    console.log(datalist, 'NFC', res6)
                  })
                  WXAPI.addCertificates(data).then(res3 => {
                    if (res3.success) {
                      var updatedata = {
                        id: res3.data,
                        status: 1
                      };
                      WXAPI.updateCertificates(updatedata).then((res2) => {});
                      console.log(res3, '添加凭证成功')
                      _this.getNfc()
                      _this.setData({
                        show: false
                      })
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加成功',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '添加失败',
                        mask: true,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                }
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '添加失败',
                mask: true,
                icon: 'none',
                duration: 2000
              })
              var datacom = {
                code: "zg/bleSendVoucherReply",
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: serialNumber,
                  index: passwordIndex,
                  type: ADD_NFC_MODE,
                  result: 0
                }
              }
              WXAPI.sendCommand(datacom).then(res2 => {
                console.log(res2, '失败')
                _this.setData({
                  show: false
                })
              })
            }
          }).catch(err => {
            var datacom = {
              code: "zg/bleSendVoucherReply",
              data: {
                lockerId: deviceinfo.deviceNum,
                serialNumber: serialNumber,
                index: passwordIndex,
                type: ADD_NFC_MODE,
                result: 0
              }
            }
            WXAPI.sendCommand(datacom).then(res2 => {
              _this.setData({
                show: false
              })
            })
            wx.showToast({
              title: '添加失败',
              mask: true,
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          wx.showToast({
            title: res.msg,
            duration: 2000,
            mask: true,
            icon: 'none'
          })
        }
      })
    } else if (deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241) {
      if (this.data.isSearch) {
        wx.hideLoading()
        this.addRfCard()
      } else {
        this.searchDevicesMethods()
      }
    }
  },
  addRfCard: function () {
    console.log("3691NFC");
    var that = this
    taskId = 61
    that.initBluetooth()
  },
  onAddRfCard: function () {
    var that = this
    wx.showLoading({
      title: '添加房卡中',
    })
    var startTime = new Date(Number(moment(that.data.starttime).format('x')))
    var endTime = new Date(Number(moment(that.data.endtime).format('x')))
    console.log("锁", lockDevice.name, basecode, 0, rfCardIndex, startTime, endTime);
    var bytes = plugin.addRfCard(lockDevice.name, basecode, 0, rfCardIndex, startTime, endTime)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },
  addRfcardCertificates() {
    var that = this
    var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
    var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
    var passwordStartTime = time1.getTime() / 1000
    var passwordEndTime = time2.getTime() / 1000
    var pzname = '',
      cardName = '';
    pzname = '蓝牙-NFC' + (that.data.passwordList.length + 1)
    cardName = that.data.personLi.name + '-蓝牙-NFC' + (that.data.passwordList.length + 1)
    let carNoId = rfCardId
    var datacom = {
      code: "ble/bleSendVoucherReply",
      data: {
        deviceNum: that.data.deviceinfo.deviceNum,
        serialNumber: serialNumber,
        index: rfCardIndex,
        type: ADD_NFC_MODE,
        cardNo: rfCardId.toUpperCase(),
        result: 1,
        productId: that.data.deviceinfo.manufactureId
      }
    }
    WXAPI.sendCommand(datacom).then(res2 => {
      if (res2.success) {
        var str = {
          // cardId: this.personInfo.cardId,
          pzname: pzname,
          imei: that.data.deviceinfo.imei,
          password: carNoId.toUpperCase(),
          blueCardNo: rfCardIndex,
          userTelephone: JSON.parse(that.data.personLi.info).userTelephone,
          operateMode: 10,
          userPassword: JSON.parse(that.data.personLi.info).userPassword,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          is: false,
          index: rfCardIndex,
          roomName: that.data.deviceinfo.roomName,
        }
        var data2 = {
          cardId: that.data.personLi.cardId,
          content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
          deviceNum: that.data.deviceinfo.deviceNum,
          type: 3,
          blueCardNo: carNoId,
          imei: that.data.deviceinfo.imei,
          serial: serialNumber,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
        };
        console.log(data2, '添加凭证')

        var datalist = {
          cardId: that.data.personLi.cardId,
          content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
          type: 13,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
        };
        WXAPI.addCertificates(datalist).then(res6 => {
          console.log(datalist, 'NFC', res6)
        })
        WXAPI.addCertificates(data2).then(res3 => {
          if (res3.success) {
            var updatedata = {
              id: res3.data,
              status: 1
            };
            WXAPI.updateCertificates(updatedata).then((res2) => {});
            console.log(res3, '添加凭证成功')
            that.getNfc()
            that.setData({
              show: false
            })
            wx.hideLoading()
            wx.showToast({
              title: '添加成功',
              mask: true,
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '添加失败',
              mask: true,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.showToast({
          title: res2.message,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  sendAddRfcard() {
    var that = this
    var info = JSON.parse(this.data.personLi.info)
    let deviceinfo = this.data.deviceinfo
    var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
    var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
    var passwordStartTime = time1.getTime() / 1000
    var passwordEndTime = time2.getTime() / 1000
    var pzname = '',
      cardName = ''
    if(that.data.pzname == ''){
      pzname = '蓝牙-NFC' + (that.data.NfcList.length + 1)
    }else{
      pzname = '蓝牙-NFC' + that.data.pzname
    }
    cardName = that.data.personLi.name + '-蓝牙-NFC' + (that.data.NfcList.length + 1)
    rfCardId = randomMethods()
    var dataPasswod = {
      code: "lwj/cardOperate",
      data: {
        lockerId: deviceinfo.deviceNum,
        lockerUserId: info.userId,
        startTime: passwordStartTime,
        endTime: passwordEndTime,
        order: 6210,
        operateMode: 10,
        action: 1,
        cardNo: rfCardId,
        type: 10,
        roomName: this.data.deviceinfo.roomName,
        cardName: cardName,
      }
    }
    console.log("平台", dataPasswod);
    WXAPI.sendCommand(dataPasswod).then(res => {
      console.log(res, '获取索引')
      if (res.success) {
        var pwdNo = res.data.index
        serialNumber = res.data.serialNumber
        rfCardIndex = pwdNo
        setTimeout(() => {
          that.onAddRfCard()
        }, 500)
      }
    })
  },
  processCardNumber(cardNo) {
    var str1 = cardNo.substr(0, 8)
    var str2 = cardNo.substr(8, 8)
    var num = str2.split("")
    var status = num.every(item => item == 0)
    console.log(status, num, 'numnum', str1, str2)
    if (status) {
      var bbb = str1.split("")
      var a, b;
      var aIndex = 0;
      var bIndex = 1;
      var arr = [];
      bbb.forEach((str, index) => {
        if (index % 2 === 0) {
          a = str;
          aIndex += 1
        } else {
          b = str
          bIndex += 1
        }
        if (a && b && (bIndex - aIndex === 1)) {
          arr.push(a + b)
        }
      });
      console.log(arr)
      return arr.join("")
    } else {
      var ll = str1 + str2
      return ll
    }
  },
  sendFp() {
    var time3 = new Date(this.data.datetimerange[0].replace(/-/g, '/'))
    var time4 = new Date(this.data.datetimerange[1].replace(/-/g, '/'))
    var passwordStartTimecontrast = time3.getTime() / 1000
    var passwordEndTimecontrast = time4.getTime() / 1000
    if (passwordStartTimecontrast > passwordEndTimecontrast) {
      wx.showToast({
        title: '开始时间不能大于结束时间',
        duration: 2000,
        mask: true,
        icon: 'none'
      })
      return
    }
    if (this.data.radioDetil == '') {
      wx.showToast({
        title: '请选择是那个指纹？',
        mask: true,
        duration: 2000,
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '正在添加指纹',
      mask: true
    })
    var _this = this
    var deviceinfo = this.data.deviceinfo
    var info = JSON.parse(this.data.personLi.info)
    if (deviceinfo.manufactureId == 101) {
      let deviceNum = deviceinfo.deviceNum
      this.setData({
        backstatus: true
      })
      var timestamp = moment().format("x")
      var time1 = moment(this.data.datetimerange[0]).format("YYYYMMDDHHmmss")
      var time2 = moment(this.data.datetimerange[1]).format("YYYYMMDDHHmmss")
      bleall.startFp_29(deviceNum, 0x03, timestamp, function (res) {
        console.log(res, 'resresres')
        if (res.success) {
          wx.showLoading({
            title: '正在添加指纹',
            mask: true
          })
        }
        if (res.data == "蓝牙功能暂不支持") {
          wx.hideLoading()
          _this.startconnect()
        }
      })

    } else if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      var cgInfo = this.data.cgInfo
      var time1 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
      var time2 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
      var passwordStartTime = time1.getTime() / 1000
      var passwordEndTime = time2.getTime() / 1000
      var cardName = '',
        pzname = ''
      if (this.data.pzname) {
        cardName = _this.data.personLi.name + '-蓝牙-' + _this.data.pzname
        pzname = '蓝牙-' + _this.data.pzname
      } else {
        cardName = _this.data.personLi.name + '-蓝牙-指纹' + (_this.data.FpList.length + 1)
        pzname = '蓝牙-指纹' + (_this.data.FpList.length + 1)
      }
      var dataPasswod = {
        code: "zg/addFingerPrint",
        data: {
          lockerId: deviceinfo.deviceNum,
          imei: deviceinfo.imei,
          lockerUserId: info.userPassword,
          keyId: info.userPassword,
          fingerType: 0,
          order: 6216,
          fingerId: '',
          roomName: deviceinfo.roomName,
          cardName: cardName,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          file: '',
          type: 1
        }
      }
      WXAPI.sendCommand(dataPasswod).then(res => {
        console.log(res, '获取索引')
        if (res.success) {
          var startTime = passwordStartTime.toString(16).toUpperCase()
          var endTime = passwordEndTime.toString(16).toUpperCase()
          info.startTime = startTime
          info.endTime = endTime
          methods.bluetoothOperation_ZH(cgInfo, info, 5).then(result => {
            if (result.status == '00' && result.completeFlag == '01') {
              console.log(result, 'callback2callback2')
              var datacom = {
                code: "zg/bleSendVoucherReply",
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: res.data.serialNumber,
                  index: result.fingerprintNo,
                  type: 16,
                  result: 1
                }
              }
              console.log(datacom)
              var str = {
                // cardId: this.personInfo.cardId,
                imei: _this.data.deviceinfo.imei,
                pzname: pzname,
                password: '',
                fingerprintAlias: _this.data.radioDetil,
                userTelephone: JSON.parse(_this.data.personLi.info).userTelephone,
                operateMode: 16,
                userPassword: JSON.parse(_this.data.personLi.info).userPassword,
                passwordStartTime: passwordStartTime,
                passwordEndTime: passwordEndTime,
                is: false,
                pass: true
              }
              var data = {
                cardId: _this.data.personLi.cardId,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                deviceNum: _this.data.deviceinfo.deviceNum,
                type: 1,
                imei: _this.data.deviceinfo.imei,
                serial: res.data.serialNumber,
                startTime: passwordStartTime,
                endTime: passwordEndTime,
                status: 1
              };
              var datalist = {
                cardId: _this.data.personLi.cardId,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: 11,
                startTime: passwordStartTime,
                endTime: passwordEndTime
              };
              WXAPI.addCertificates(datalist).then(res6 => {})
              console.log(data, '添加凭证')
              WXAPI.addCertificates(data).then(res3 => {
                if (res3.success) {
                  var updatedata = {
                    id: res3.data,
                    status: 1
                  };
                  WXAPI.updateCertificates(updatedata).then((res2) => {});
                  WXAPI.sendCommand(datacom).then(res2 => {
                    if (res2.success) {}
                  })
                  console.log(res3, '添加凭证成功')
                  _this.getFp()
                  _this.setData({
                    show: false
                  })
                  wx.hideLoading()
                  wx.showToast({
                    title: '添加成功',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '添加失败',
                    mask: true,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          }).catch(err => {
            var datacom = {
              code: "zg/bleSendVoucherReply",
              data: {
                lockerId: deviceinfo.deviceNum,
                serialNumber: res.data.serialNumber,
                index: 0,
                type: 16,
                result: 0
              }
            }
            WXAPI.sendCommand(datacom).then(res2 => {
              if (res2.success) {}
            })
          })
        } else {
          var datacom = {
            code: "zg/bleSendVoucherReply",
            data: {
              lockerId: deviceinfo.deviceNum,
              serialNumber: res.data.serialNumber,
              index: 0,
              type: 16,
              result: 0
            }
          }
          WXAPI.sendCommand(datacom).then(res2 => {
            if (res2.success) {}
          })
          wx.showToast({
            title: res.msg,
            duration: 2000,
            mask: true,
            icon: 'none'
          })
        }
      })
    } else if (deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241) {
      if (this.data.isSearch) {
        // fingerprintIndex = 1
        // serialNumber = 1686309639840
        // this.onAddFingerprint()
        // return
        var time1 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
        var time2 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
        var passwordStartTime = time1.getTime() / 1000
        var passwordEndTime = time2.getTime() / 1000
        var cardName = '',
          pzname = ''
        if (this.data.pzname) {
          cardName = _this.data.personLi.name + '-蓝牙-' + _this.data.pzname
          pzname = '蓝牙-' + _this.data.pzname
        } else {
          cardName = _this.data.personLi.name + '-蓝牙-指纹' + (_this.data.FpList.length + 1)
          pzname = '蓝牙-指纹' + (_this.data.FpList.length + 1)
        }
        var dataPasswod = {
          code: "lwj/fpOperate",
          data: {
            lockerId: deviceinfo.deviceNum,
            action: 1,
            lockerUserId: info.userPassword,
            fpData: '',
            operateMode: 16,
            order: 6216,
            roomName: deviceinfo.roomName,
            cardName: cardName,
            startTime: passwordStartTime,
            endTime: passwordEndTime,
            type: 1
          }
        }
        WXAPI.sendCommand(dataPasswod).then(res => {
          if (res.success) {
            fingerprintIndex = res.data.index
            serialNumber = res.data.serialNumber
            this.onAddFingerprint()
          }
        })
      } else {
        this.searchDevicesMethods()
      }
    }
  },

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

    var bytes = plugin.login1(lockDevice.name, basecode)
    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分钟
    var startTime = new Date(Number(moment(that.data.starttime).format('x')))
    var endTime = new Date(Number(moment(that.data.endtime).format('x')))
    // fingerprintIndex = Math.floor(Math.random() * 100)
    var bytes = plugin.addFingerprint(lockDevice.name, basecode, fingerprintIndex, startTime, endTime)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },
  // 关闭添加人员弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  onChange(event) {
    console.log(event.detail)
    this.setData({
      activeKey: event.detail
    })
  },
  getPassword() {
    var data = {
      pageNum: 0,
      pageSize: 0,
      q: JSON.stringify({
        cardId: this.data.personLi.cardId,
        deviceNum: this.data.deviceinfo.deviceNum,
        types: "4",
        inStatus: '0,1,702'
      })
    }
    console.log(data)
    WXAPI.getCertificates(data).then(res => {
      var dataOne = util.zlib_unzip(res.data)
      if (res.success) {
        dataOne.map(li => {
          li['pzname'] = JSON.parse(li.content).pzname
          li['password'] = util.plusXing(JSON.parse(li.content).password, 2, 2, '*')
        })
        this.setData({
          passwordList: dataOne
        })
      }
    })
  },
  getNfc() {
    var data = {
      pageNum: 0,
      pageSize: 0,
      q: JSON.stringify({
        cardId: this.data.personLi.cardId,
        deviceNum: this.data.deviceinfo.deviceNum,
        types: "3",
        inStatus: '0,1,702'
      })
    }
    WXAPI.getCertificates(data).then(res => {
      console.log(res)
      var dataOne = util.zlib_unzip(res.data)
      console.log(dataOne)
      if (res.success) {
        dataOne.map(li => {
          li['pzname'] = JSON.parse(li.content).pzname
          li['password'] = util.plusXing(JSON.parse(li.content).password, 2, 2, '*')
        })
        this.setData({
          NfcList: dataOne
        })
      }
    })
  },
  getFp() {
    var data = {
      pageNum: 0,
      pageSize: 0,
      q: JSON.stringify({
        cardId: this.data.personLi.cardId,
        deviceNum: this.data.deviceinfo.deviceNum,
        types: "1",
        inStatus: '0,1,702'
      })
    }
    WXAPI.getCertificates(data).then(res => {
      var dataOne = util.zlib_unzip(res.data)
      if (res.success) {
        dataOne.map(li => {
          li['pzname'] = JSON.parse(li.content).pzname
          li['password'] = ''
          li['fingerprintAlias'] = JSON.parse(li.content).fingerprintAlias || ''
        })
        this.setData({
          FpList: dataOne
        })
      }
    })
  },
  getCarId() {
    var data = {
      pageNum: 0,
      pageSize: 0,
      q: JSON.stringify({
        cardId: this.data.personLi.cardId,
        deviceNum: this.data.deviceinfo.deviceNum,
        types: "2",
        inStatus: '0,1,702'
      })
    }
    WXAPI.getCertificates(data).then(res => {
      var dataOne = util.zlib_unzip(res.data)
      if (res.success) {
        dataOne.map(li => {
          li['pzname'] = JSON.parse(li.content).pzname
          li['password'] = util.plusXing(JSON.parse(li.content).password, 2, 2, '*')
        })
        this.setData({
          CarIdList: dataOne
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (isConnected) {
      console.log(connectedDeviceId, 'connectedDeviceId')
      wx.closeBLEConnection({
        deviceId: connectedDeviceId,
        success: function (res) {
          isConnected = false
          app.globalData.isConnected = false
        },
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

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

  },

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

  }
})