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

  /**
   * 页面的初始数据
   */
  data: {
    passwordStatus:false,
    addpassword:'',
    showTwo:false,
    showOne:false,
    starttime:'',
    endtime:'',
    minDate: '',
    minDate1: '',
    info: "", //显示框
    deviceinfo: {
      rssi: 0,
      battery: 0,
      lockStatus: 0,
      isOnline: 0,
      event: '',
      bleStatus: ''
    },
    index: 0,
    fingerprintId: '',
    openlock: '',
    IssuingPersonnel: true,
    backstatus: false,
    cgInfo: '',
    zgBlueStatus: false,
    timer: '',
    count: 0,
    show: false,
    actions: [{
        name: '静音',
        color: '#ee0a24'
      },
      {
        name: '低音',
        color: '#333'
      },
      {
        name: '高音',
        color: '#333'
      },
    ],
    volume: '',
    bluestatus: app.globalData.backstatus,
    show1: false,
    TemporaryPassword: '',
    phone: '',
    userInfo: {
      type: ''
    },
    authority: false,
    showbuleKey:false,
    deviceList:[],
    userRole:'',
    passwordList:[],
    NfcList:[],
    remotePasswordStatus:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userRole = wx.getStorageSync('userRole') || ''
    this.setData({
      userRole
    })
    app.globalData.zgBlueStatus = false
    this.AddressPermissions()
    let deviceinfo = wx.getStorageSync('deviceinfo')
    if(deviceinfo.manufactureId==201||deviceinfo.manufactureId == 221){      
      var data3 = {
        code: "zg/bleRegisterInfo",
        signature:wx.getStorageSync('signature'),
        cardId:deviceinfo.cardId,
        data: {
          lockerId: deviceinfo.deviceNum
        }
      }
      WXAPI.sendCommandOne(data3).then(res1 => {
        if (res1.success) {
          wx.setStorageSync('cgInfo', res1.data)
          this.setData({
            cgInfo: res1.data
          })
        } else {

        }
      })
    }else{

    }
    this.getApartmentCardInfoMethods()
    this.getPassWordMehods()
    app.globalData.deviceNum = deviceinfo.deviceNum
    app.watch(this.getcartcount, 'backdata')
    app.watch(this.fingerprintFun, 'fingerprintId')
    app.watch(this.openlockfun, 'openlock')
  },
  // 获取合同信息
  getApartmentCardInfoMethods(){
    let deviceinfoList = wx.getStorageSync('deviceinfoList')
    if(deviceinfoList[0].cardId){
      let data={
        signature:wx.getStorageSync('signature'),
        id:deviceinfoList[0].cardId,
      }
      WXAPI.getApartmentCardInfo(data).then(res=>{
        if(res.success){
          let leases = res.data.leases
          if(leases.length>0){
            let leasesObject = leases[leases.length-1]
            let minDate = moment(leasesObject.signingTime).format('YYYY-MM-DD')
            let minDate1 = moment(leasesObject.contractTime).format('YYYY-MM-DD')
            this.setData({
              minDate:minDate,
              minDate1:minDate1
            })
          }else{
            wx.showToast({
              title: "还未签订合同",
              duration: 2000,
              icon: 'none'
            })
          }
        }else{
          wx.showToast({
            title: "获取合同信息失败",
            duration: 2000,
            icon: 'none'
          })
        }
      })
    }else{
      wx.showToast({
        title: "还未有对应合同",
        duration: 2000,
        icon: 'none'
      })
    }
  },
  // 添加远程密码
  addRemotePassword(){
    this.setData({
      showTwo:true,
      remotePasswordStatus:true
    })
  },
  // 前往密码列表
  goPasswordList(){
    wx.navigateTo({
      url: '/pagesA/passwordList/passwordList',
    })
  },
  // 交租跳转
  payRentMethods(){
    wx.navigateTo({
      url: '/pages/rentDetail/rentDetail',
    })
  },
  onCloseBlue(){
    this.setData({
      showbuleKey:false
    })
  },
  onCloseTwo(){
    this.setData({
      showTwo:false,
      remotePasswordStatus:false
    })
  },
  onCloseOne(){
    this.setData({
      showOne:false
    })
  },
  // 选择开始结束时间
  bindDateChangeAdd(e){
    var str = e.detail.value + " 00:00:00"
    this.setData({
      starttime: str
    })
  },
  bindDateChangeAddTwo(e){
    var str = e.detail.value + " 00:00:00"
    this.setData({
      endtime: str
    })
  },
  addUser(){
    var cgInfo=this.data.cgInfo
    ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
      (callback) => {
        if (callback.status == '00') {
          ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, callback.signKey, (callback1) => {
            if (callback1.status == '00') {
              ICINLocker.addUserToLock(cgInfo.lockerId, cgInfo.superId, "BLEKEY_8d82e5d527e1", "0o01weit9ti9ti", "00", callback.signKey, "", callback1.commonKey, "00000000", "FFFFFFFF", (callback) => {
                console.log(callback)
              })
            }
          })
        }
      })
  },
  stringToHex(str){
　　　　var val="";    
　　　　for(var i = 0; i < str.length; i++){    
　　　　　　if(val == "")    
　　　　　　　　val = str.charCodeAt(i).toString(16);    
　　　　　　else    
　　　　　　　　val += str.charCodeAt(i).toString(16);    
　　　　}    
　　　　return val;    
　　},
  linkBlue(){
    wx.navigateTo({
      url: '/pages/addBlueButton/addBlueButton',
    })    
  },
  searchBlueButton(e) {
    var that = this
    var cgInfo=this.data.cgInfo
    var comm=this.stringToHex(e.currentTarget.dataset.select.name)
    console.log(comm)
    var deviceId=e.currentTarget.dataset.select.deviceId
    var keyId="0o01weit9ti9ti"
    var password="3030000000000000000000000000000000000000"
    app.globalData.blueDeviceId = e.currentTarget.dataset.select.name
    var blueKeyId=e.currentTarget.dataset.select.name
    ICINLocker.connect(deviceId,true) // 此处 deviceId 存起来，当断开连接时使用
            .then((res) => {
              if (res.status == 0) {
                clearInterval(that.data.timer)
                this.setData({
                  bleStatus: '蓝牙已连接',
                  deviceId: deviceId
                })
                app.globalData.zgBlueStatus = true
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  duration: 2000
                })
                ICINLocker.readBluetoothBuckle(cgInfo.lockerId, comm, callback2 => {
                  if(callback2.status==0){
                    ICINLocker.registeBluetoothBuckle(cgInfo.superId, blueKeyId, keyId, password, "", cgInfo.authKey, comm, callback3 => {
                      if(callback3.status==0){
                        wx.hideLoading()
                        wx.showToast({
                          title: '添加成功',
                          duration:2000,
                          icon:"none"
                        })
                      }else{
                        wx.hideLoading()
                        wx.showToast({
                          title: '添加成功',
                          duration:2000,
                          icon:"none"
                        })
                      }
                    })
                  }else{
                    wx.hideLoading()
                    wx.showToast({
                      title: '读取失败',
                      duration:2000,
                      icon:"none"
                    })
                  }
                });
              } else {
                wx.hideLoading()
                var msg = ''
                switch (res.errCode) {
                  case 10001:
                    msg = '调用失败，请打开蓝牙！';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  icon: 'none'
                })
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              console.log(res, '失败')
              // 此处处理未能连接成功问题
            })    
  },
  onChange2(event) {
    this.setData({
      addpassword: event.detail
    })
  },
  onChange(event) {
    this.setData({
      phone: event.detail
    })
  },
  // 发送临时密码
  sendMessage() {
    var re = /^1\d{10}$/
    if (re.test(this.data.phone)) {
      var data = {
        code: this.data.TemporaryPassword,
        phone: this.data.phone,
        device: this.data.deviceinfo.deviceNum,
        name: this.data.deviceinfo.roomName
      }
      WXAPI.sendEmergence(data).then(res => {
        if (res.success) {
          this.setData({
            show1: false
          })
          wx.showToast({
            title: "发送成功",
            duration: 2000,
            icon: "none"
          })
        } else {
          wx.showToast({
            title: "发送失败",
            duration: 2000,
            icon: "none"
          })
        }
      })
    } else {
      wx.showToast({
        title: "请输入正确的手机号",
        duration: 2000,
        icon: "none"
      })
    }
  },
  // 获取临时密码
  getTemporaryPassword() {
    var data = {
      code: "zg/getEmergence",
      signature:wx.getStorageSync('signature'),
      cardId:this.data.deviceinfo.cardId,
      data: {
        lockerId: this.data.deviceinfo.deviceNum
      }
    }
    WXAPI.sendCommandOne(data).then(res => {
      if (res.success) {
        this.setData({
          TemporaryPassword: res.data.data,
          show1: true
        })
      } else {
        wx.showToast({
          title: "获取失败",
          duration: 2000,
          icon: "none"
        })
      }
    })
  },
  // 关闭临时密码弹窗
  onClose1() {
    this.setData({
      show1: false
    });
  },
  // 关闭设置音量
  onClose() {
    this.setData({
      show: false
    });
  },
  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
    }
  },
  sendNfc() {
    var time3 = new Date(this.data.starttime)
    var time4 = new Date(this.data.endtime)
    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.deviceinfo.info)
    if (deviceinfo.manufactureId == 101) {
      
    } else if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 221) {
      var cgInfo = this.data.cgInfo
      var passwordStartTime = passwordStartTimecontrast
      var passwordEndTime = passwordEndTimecontrast
      var pzname='',cardName=''
      if(pzname==""){
        pzname=_this.data.deviceinfo.name+'-蓝牙-NFC'+(_this.data.NfcList.length+1)
        cardName=_this.data.deviceinfo.name+'-蓝牙-NFC'+(_this.data.NfcList.length+1) 
      }else{
        pzname=_this.data.deviceinfo.name+'-蓝牙-'+pzname
        cardName=_this.data.deviceinfo.name+'-蓝牙-'+pzname
      } 
      var dataPasswod = {
        code: "zg/cardOperate",
        cardId:deviceinfo.cardId,
        data: {
          lockerId: deviceinfo.deviceNum,
          imei: deviceinfo.imei,
          lockerUserId: info.userPassword,
          keyId: info.userPassword,
          action: 1,
          taskStatus: 1,
          order: 6210,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          cardType: 50,
          type: ADD_NFC_MODE,
          roomName: this.data.deviceinfo.roomName,
          cardName: cardName,          
          operateName:_this.data.deviceinfo.name
        },
        signature:wx.getStorageSync('signature'),
      }
      console.log(dataPasswod,'dataPasswod')
      WXAPI.sendCommandOne(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",
                cardId:deviceinfo.cardId,
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: serialNumber,
                  index: passwordIndex,
                  type: ADD_NFC_MODE,
                  cardNo: carNoId.toUpperCase(),
                  result: 1,
                  operateName:_this.data.deviceinfo.name
                },
                signature:wx.getStorageSync('signature'),
              }
              WXAPI.sendCommandOne(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: info.userTelephone,
                    operateMode: 10,
                    userPassword: info.userPassword,
                    passwordStartTime: passwordStartTime,
                    passwordEndTime: passwordEndTime,
                    is: false,
                    roomName:_this.data.deviceinfo.roomName,
                  }
                  var data = {
                    cardId: _this.data.deviceinfo.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,
                    signature:wx.getStorageSync('signature'),
                  };
                  console.log(data, '添加凭证')
                  
                  var datalist = {
                    cardId: _this.data.deviceinfo.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 13,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                    signature:wx.getStorageSync('signature'),
                  };
                  WXAPI.tsAddCertificate(datalist).then(res6 => {                      
                    console.log(datalist,'NFC',res6)
                  })
                  WXAPI.tsAddCertificate(data).then(res3 => {
                    if (res3.success) {
                      var updatedata = {
                        id: res3.data,
                        status:1,
                        signature:wx.getStorageSync('signature'),
                      };
                      WXAPI.editCertificate(updatedata).then((res2) => {
                      });
                      console.log(res3, '添加凭证成功')
                      _this.setData({
                        showOne: false
                      })
                      _this.getPassWordMehods()
                      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",
                cardId:deviceinfo.cardId,
                data: {
                  lockerId: deviceinfo.deviceNum,
                  serialNumber: serialNumber,
                  index: passwordIndex,
                  type: ADD_NFC_MODE,
                  result: 0
                },
                signature:wx.getStorageSync('signature'),
              }
              WXAPI.sendCommandOne(datacom).then(res2 => {
                console.log(res2, '失败')
                _this.setData({
                  showOne: false
                })
              })
            }
          })
        } else {
          wx.showToast({
            title: res.msg,
            duration: 2000,
            mask:true,
            icon: 'none'
          })
        }
      })
    }
  },
  // 选择设置音量
  onSelect(event) {
    var volume = '',
      volume1 = ''
    if (event.detail.name == '静音') {
      volume = '00'
      volume1 = 0
    } else if (event.detail.name == '低音') {
      volume = '01'
      volume1 = 1
    } else if (event.detail.name == '高音') {
      volume = '02'
      volume1 = 2
    }
    this.setData({
      volume: volume
    })
    wx.showLoading({
      title: "正在设置...",
    });
    if (this.data.deviceinfo.manufactureId == 201||this.data.deviceinfo.manufactureId == 221) {
      this.setVolume(volume)
    } else if (this.data.deviceinfo.manufactureId == 101) {
      this.setVolume1(volume)
    }
  },
  fingerprintFun() {
    this.data.fingerprintId = app.globalData.fingerprintId
  },
  // 人员管理
  personManger() {
    wx.navigateTo({
      url: '/pages/personManger/personManger',
    })
  },
  openlockfun() {
    var that = this
    this.data.openlock = app.globalData.openlock
    var userInfo=wx.getStorageSync('deviceinfo')
    if (app.globalData.openlock == 1) {
      var data = {
        code: "ld/bleUnlockRecord",
        signature:wx.getStorageSync('signature'),
        cardId:this.data.deviceinfo.cardId,
        data: {
          deviceNum: this.data.deviceinfo.deviceNum,
          userTelephone: "18270949468",
          password: "2021",
          roomId:that.data.deviceinfo.roomId,
          roomName:that.data.deviceinfo.roomName,
          cardName:userInfo.name,
        }
      }
      console.log(data)
      WXAPI.sendCommandOne(data).then(res => {

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

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

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

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

    let b = new Uint8Array(length)

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

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

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

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

    b[71] = 0xff;

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

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

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

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

    let b = new Uint8Array(length)

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

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

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

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

    b[71] = 0xff;

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

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


  startFp_29(deviceNum, status) {

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

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

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

    let b = new Uint8Array(length)

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

    //send data=0x0036000008 
    b[21] = 0x00;
    b[22] = 0x36;
    b[23] = 0;
    b[24] = 0;
    b[25] = 0x08
    b[26] = status //status: 0x03, 0x02, 0x01
    b[27] = 0x01
    app.globalData.ble.send(cmd, b)
  },
  // 设置密码
  permissionsfun() {
    wx.navigateTo({
      url: "/pages/permissions/permissions"
    })
  },
  // 跳转开锁记录页面
  getlogList() {
    wx.navigateTo({
      url: "/pages/openLockLog/openLockLog?&roomId=" + this.data.deviceinfo.roomId+"&cardId="+this.data.deviceinfo.cardId
    })
  },
  // zg蓝牙连接
  openTheDoor() {
    // if(this.data.deviceinfo.info){
      // JSON.parse(this.data.deviceinfo.info)
      // var deviceinfo = this.data.deviceinfo
    var userInfo = wx.getStorageSync('deviceinfo')
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, (callback) => {
      console.log(callback)
      if (callback.status == '00') {
        var userSignKey = callback.signKey
        ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, userSignKey, (callback) => {
          console.log(callback)
          var commonKey = callback.commonKey
          ICINLocker.openTheDoor(this.data.cgInfo.lockerId, this.data.cgInfo.superId, userSignKey, this.data.cgInfo.superId, '', '01', commonKey, (callback) => {
            var data = {
              code: "zg/bleUnlockRecord",
              signature:wx.getStorageSync('signature'),
              cardId:this.data.deviceinfo.cardId,
              data: {
                lockerId: this.data.cgInfo.lockerId,
                lockerUserId: this.data.cgInfo.superId,
                roomId:this.data.deviceinfo.roomId,
                roomName:this.data.deviceinfo.roomName,
                cardName:userInfo.name,
                operateName:this.data.deviceinfo.name
              }
            }
            WXAPI.sendCommandOne(data).then(res => {
              console.log(res)
            })
          })
        })
      }
    });
    // }else{
    //   wx.showToast({
    //     title: '请先下发人员',
    //     duration:2000,
    //     icon:'none'
    //   })
    // }    
  },
  // 退出登录
  loginOut(){
    console.log(1111)
    wx.removeStorage({
      key:"signature"
    })
    wx.redirectTo({
      url:"/pages/login/login"
    })
  },
  // 添加指纹
  addFingerPrints() {
    var userInfo = JSON.parse(this.data.deviceinfo.info)
    ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, this.data.cgInfo.authKey, (callback) => {
      ICINLocker.addFingerPrints(this.data.cgInfo.lockerId, this.data.cgInfo.superId, userInfo.userPassword, this.data.cgInfo.superId, '', this.data.cgInfo.authKey, '00000000', 'FFFFFFFF', '00', callback.commonKey, (callback) => {
        console.log(callback)
      })
    })
  },
  // 蓝牙初始化
  btntest1(e) {
    var event = e.currentTarget.dataset.i
    var that = this;
    this.data.event = event
    var deviceinfo = this.data.deviceinfo
    this.setData({      
      remotePasswordStatus:false
    })
    if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 221) {
      if (app.globalData.zgBlueStatus) {
        if (event == 0) {
          this.openTheDoor()
        } else if (event == 1) {
          this.addPassword()
        }else if (event == 3) {
          this.addFingerPrints()
        } else if (event == 6) {
          this.setData({
            show: true
          })
        }else if (event == 11) {
          this.setData({
            showOne: true
          })
        }else if (event == 12) {
          this.goPasswordList()
        }
      } else {
        that.goBlue()
      }
    } else if (deviceinfo.manufactureId == 101) {
      if (app.globalData.bleStatus == '蓝牙已连接') {
        if (event == 0) {
          this.btntest2()
        } else if (event == 1) {
          this.addPassword()
        }else if (event == 3) {
          this.btntest3()
        } else if (event == 6) {
          // this.setVoice()
          this.setData({
            show: true
          })
        } else if (event == 7) {
          wx.showModal({
            title: "常开设置",
            cancelText: '关闭',
            confirmText: '开启',
            success: (res) => {
              if (res.confirm) {
                that.setOpen()
              } else if (res.cancel) {
                that.setOpen1()
              }
            }
          })
        }
      } else {
        this.startconnect()
      }
    }
  },
  goBlue() {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    console.log(this.data.deviceinfo.deviceNum, 'this.data.deviceinfo.deviceNum')
    ICINLocker.scanDevices(this.data.deviceinfo.deviceNum)
      .then((res) => {
        console.log(res)
        if (res.status == 0) {
          var deviceId = res.deviceId
          //成功找到蓝牙情况下进行锁连接
          app.globalData.blueDeviceId = res.deviceId
          ICINLocker.connect(res.deviceId,false) // 此处 deviceId 存起来，当断开连接时使用
            .then((res) => {
              if (res.status == 0) {
                clearInterval(that.data.timer)
                this.setData({
                  bleStatus: '蓝牙已连接',
                  deviceId: deviceId
                })
                app.globalData.zgBlueStatus = true
                wx.hideLoading()
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  duration: 2000
                })
                if (this.data.event == 0) {
                  this.openTheDoor()
                }else if(this.data.event == 1){
                  this.addPassword()
                } else if (this.data.event == 3) {
                  this.addFingerPrints()
                } else if (this.data.event == 6) {
                  this.setData({
                    show: true
                  })
                }else if(this.data.event == 11){                  
                  this.setData({
                    showOne: true
                  })
                }else if (event == 12) {
                  this.goPasswordList()
                }
              } else {
                wx.hideLoading()
                var msg = ''
                switch (res.errCode) {
                  case 10001:
                    msg = '调用失败，请打开蓝牙！';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  icon: 'none'
                })
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              console.log(res, '失败')
              // 此处处理未能连接成功问题
            })
        }
      })
      .catch((res) => {
        //此处处理未能连接到蓝牙的问题
        if (res.status == 1) {
          if (res.statusReason.errCode == 10001) {
            wx.hideLoading()
            wx.showToast({
              title: '请检查手机蓝牙和定位功能是否打开？',
              duration: 2000,
              icon: 'none'
            })
          } else {
            if (!app.globalData.zgBlueStatus && that.data.bluestatus) {
              that.goBlue()
            } else {
              wx.hideLoading()
            }
          }
        }
      })
  },

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

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

    let length = 2

    let b = new Uint8Array(length)

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

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

    })
  },
  setVolume(volume) {
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
      (callback) => {
        console.log(callback, '-----')
        if (callback.status == '00') {
          ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, callback.signKey, (callback1) => {
            console.log(callback1, '2222222')
            if (callback1.status == '00') {
              ICINLocker.setVolume(this.data.cgInfo.lockerId, this.data.cgInfo.superId, volume, callback1.commonKey, (callback2) => {
                console.log(callback2, '333333333')
                if (callback2.status == '00') {
                  wx.hideLoading()
                  wx.showToast({
                    title: '设置成功',
                    duration: 2000,
                    icon: 'none'
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '设置失败',
                    duration: 2000,
                    icon: 'none'
                  })
                }
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '设置失败',
                duration: 2000,
                icon: 'none'
              })
            }
          })
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '设置失败',
            duration: 2000,
            icon: 'none'
          })
        }
      });
  },
  //设置常开
  setOpen() {
    wx.showLoading({
      title: "正在开启...",
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

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

    let length = 2

    let b = new Uint8Array(length)

    b[0] = cmd
    b[1] = 1;
    app.globalData.ble.send(cmd, b, function (res) {})
  },
  setOpen1() {
    wx.showLoading({
      title: "正在关闭...",
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

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

    let length = 2

    let b = new Uint8Array(length)

    b[0] = cmd
    b[1] = 0;
    app.globalData.ble.send(cmd, b, function (res) {})
  },
  //设置音量
  setVoice() {

  },
  startconnect() {
    //if(checkWechatVersion())
    // {
    wx.showLoading({
      title: "连接中"
    })
    var deviceinfo = this.data.deviceinfo
    const ble = new BLE(this.data.deviceinfo.deviceNum, emitter)
    app.globalData.ble = ble
    this.watchBLE()
    app.globalData.ble.init()
    // }
  },
  watchBLE() {
    var that = this
    var deviceinfo = this.data.deviceinfo
    if (app.globalData.ble) {
      app.globalData.ble.listen(res => {
        if (res.type == 'connect') {
          if (res.data == "未打开适配器") {
            wx.hideLoading()
            wx.showToast({
              title: '请检查手机蓝牙和定位功能是否打开？',
              duration: 2000,
              icon: 'none'
            })
          } else {
            if (res.data == '蓝牙已连接') {
              this.data.info = res.data
              app.globalData.bleStatus = res.data
              if (this.data.event == 0) {
                this.btntest2()
              } else if(this.data.event == 1){
                this.addPassword()
              }else if (this.data.event == 3) {
                this.btntest3()
              } else if (this.data.event == 6) {
                // this.setVoice()
                this.setData({
                  show: true
                })
              } else if (this.data.event == 7) {
                wx.showModal({
                  title: "常开设置",
                  cancelText: '关闭',
                  confirmText: '开启',
                  success: (res) => {
                    if (res.confirm) {
                      that.setOpen()
                    } else if (res.cancel) {
                      that.setOpen1()
                    }
                  }
                })
              }
            }
          }
        }
      })
    }
  },
  // 添加密码
  addPassword(){
    this.setData({
      showTwo:true
    })
  },
  async getPassWordMehods(){
    var that=this
    let deviceinfoList = wx.getStorageSync('deviceinfo')
    var data = {
      id:deviceinfoList.cardId,
      signature:wx.getStorageSync('signature'),
    };
    WXAPI.tsGetCertificate(data).then(res=>{
      if(res.success){        
        var dataOne=[],dataTwo=[]
        res.data.map(li=>{
          if(li.type == 14){
            li.content=JSON.parse(li.content)
            dataOne.push(li)
          }else if(li.type == 13){
            li.content=JSON.parse(li.content)
            dataTwo.push(li)
          }
        })
        this.setData({
          passwordList:dataOne,
          NfcList:dataTwo
        })
      }else{
        wx.showToast({
          title: '获取失败',
          duration:'2000',
          mask:true,
          icon:'none'
        })
      }
    })
  },
  async sendPassword() {
    var addpassword = this.data.addpassword.toString()
    if(addpassword.length!=6){
      wx.showToast({
        title: '格式错误，密码为6位数字！',
        icon:'none'
      })
      return false;
    }
    var time3 = new Date(this.data.starttime)
    var time4 = new Date(this.data.endtime)
    var passwordStartTimecontrast = time3.getTime() / 1000
    var passwordEndTimecontrast = time4.getTime() / 1000
    let passwordStatus = this.data.passwordStatus
    console.log(time3,time4,passwordStartTimecontrast,passwordEndTimecontrast)
    // await this.getPassWordMehods(this.data.addpassword,this.data.deviceinfo.cardId,14)
    let paaaWd=this.data.passwordList.filter(lt=> lt.content.password == this.data.addpassword)
    if(paaaWd.length > 0){
      passwordStatus = false
    }else{
      passwordStatus = true
    }
    if(this.data.addpassword==''){
      wx.showToast({
        title: '密码不能为空',
        mask:true,
        duration: 2000,
        icon: 'none'
      })
      return
    }
    if(!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
    if(this.data.remotePasswordStatus){
      var pzname='',cardName=''
      pzname=_this.data.deviceinfo.name+'-远程-密码'+(_this.data.passwordList.length+1)
      cardName=_this.data.deviceinfo.name+'-远程-密码'+(_this.data.passwordList.length+1)      
      let dataObject={
        code: "zg/tempPassword",
        data: {
          lockerId: deviceinfo.deviceNum,
          imei: deviceinfo.imei,
          order: 6207,
          lockerUserId: JSON.parse(deviceinfo.info).userPassword,
          passwordCount: 255,
          keyId: JSON.parse(deviceinfo.info).userPassword,
          passwordStartTime: passwordStartTimecontrast,
          passwordEndTime: passwordEndTimecontrast,
          action: 1,
          password: addpassword,
          cardName: cardName,
          roomName: deviceinfo.roomName
        },
        operateName:_this.data.deviceinfo.name,
        signature:wx.getStorageSync('signature'),
        cardId: deviceinfo.cardId,
      }
      WXAPI.sendCommandOne(dataObject).then(res=>{
        if (res.success) {
          let dataPassword = {
            imei: deviceinfo.imei,
            deviceNum: deviceinfo.deviceNum,
            userTelephone: JSON.parse(deviceinfo.info).userTelephone,
            cardId: deviceinfo.cardId,
            userPassword: JSON.parse(deviceinfo.info).userPassword,
            password: addpassword,
            operateMode: 7,
            order: 6207,
            type: 4,
            passwordStartTime: passwordStartTimecontrast,
            passwordEndTime: passwordEndTimecontrast,
            is: false,
            cardName: cardName,
            roomName: deviceinfo.roomName,
            pzname: pzname,
            pass: false
          };
          var data = {
            cardId: _this.data.deviceinfo.cardId,
            content: JSON.stringify(dataPassword), //operateMode:NFC-10、把人员添加到凭证-1
            deviceNum: _this.data.deviceinfo.deviceNum,
            type: 4,
            imei: _this.data.deviceinfo.imei,
            serial: res.data.serialNumber,
            startTime: passwordStartTimecontrast,
            endTime: passwordEndTimecontrast,
            signature:wx.getStorageSync('signature'),
          };
          var datalist = {
            cardId: _this.data.deviceinfo.cardId,
            content: JSON.stringify(dataPassword), //operateMode:NFC-10、把人员添加到凭证-1
            type: 14,
            startTime: passwordStartTimecontrast,
            endTime: passwordEndTimecontrast,
            signature:wx.getStorageSync('signature'),
          };
          console.log(datalist,'密码11')
          WXAPI.tsAddCertificate(datalist).then(res6 => {
            console.log(datalist,'密码22')
          })
          wx.showToast({
            title: '下发成功',
            icon: 'none',
            mask:true,
            duration: 2000
          })
          WXAPI.tsAddCertificate(data).then(res3 => {
            if (res3.success) {
              // var updatedata = {
              //   id: res3.data,
              //   status:1,
              //   signature:wx.getStorageSync('signature'),
              // };
              // WXAPI.editCertificate(updatedata).then((res2) => {
    
              // });
              _this.getPassWordMehods()
              _this.setData({
                showTwo: 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: `${res.msg}`,
            duration:2000,
            icon:'none'
          })
        }
      })
    }else{
      if (deviceinfo.manufactureId == 101) {
        var time1 = moment(this.data.starttime).format("YYYYMMDDHHmmss")
        var time2 = moment(this.data.endTime).format("YYYYMMDDHHmmss")
        var time3 = new Date(_this.data.starttime.replace(/-/g, '/'))
        var time4 = new Date(_this.data.endTime.replace(/-/g, '/'))
        var passwordStartTime = time3.getTime() / 1000
        var passwordEndTime = time4.getTime() / 1000
        let info = JSON.parse(_this.data.deviceinfo.info)
        var data1 = {
          managerTelephone: "18270949468",
          managerPassword: '202108',
          userTelephone: info.userTelephone,
          userPassword: info.userPassword,
          password: this.data.addpassword,
          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.deviceinfo.name+'-蓝牙-密码'+(_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.addpassword,
                userTelephone: info.userTelephone,
                operateMode: 7,
                userPassword: info.userPassword,
                passwordStartTime: time1,
                passwordEndTime: time2,
                is: false,
                pass:true
              }
              var data3 = {
                code: "ble/operateUserInfo",
                signature:wx.getStorageSync('signature'),
                cardId:_this.data.deviceinfo.cardId,
                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.sendCommandOne(data3).then(res3 => {
                if (res3.success) {
                  var data4 = {
                    result: 1,
                    serial: res3.data.serialNumber
                  }
                  WXAPI.updatePush(data4).then(res4 => {
  
                  })
                  var data = {
                    cardId: _this.data.deviceinfo.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,
                    signature:wx.getStorageSync('signature'),
                  };
                  var datalist = {
                    cardId: _this.data.deviceinfo.cardId,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    type: 14,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                    signature:wx.getStorageSync('signature'),
                  };
                  console.log(datalist,'密码11')
                  WXAPI.tsAddCertificate(datalist).then(res6 => {
                    console.log(datalist,'密码22')
                  })
                  WXAPI.tsAddCertificate(data).then(res3 => {
                    if (res3.success) {
                      var updatedata = {
                        id: res3.data,
                        status:1,
                        signature:wx.getStorageSync('signature'),
                      };
                      WXAPI.editCertificate(updatedata).then((res2) => {
  
                      });
                      _this.getPassWordMehods()
                      _this.setData({
                        showTwo: 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 == "蓝牙功能暂不支持") {
                _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
        console.log(passwordStartTimecontrast,passwordEndTimecontrast)
        var passwordStartTime = passwordStartTimecontrast
        var passwordEndTime = passwordEndTimecontrast
        var pzname='',cardName=''
        console.log(_this.data.passwordList,_this.data.deviceinfo)
        pzname=_this.data.deviceinfo.name+'-蓝牙-密码'+(_this.data.passwordList.length+1)
        cardName=_this.data.deviceinfo.name+'-蓝牙-密码'+(_this.data.passwordList.length+1)
        let info = JSON.parse(_this.data.deviceinfo.info)
        var dataPasswod = {
          code: "zg/tempPassword",
          cardId:deviceinfo.cardId,
          data: {
            lockerId: deviceinfo.deviceNum,
            imei: deviceinfo.imei,
            passwordCount: 255,
            lockerUserId: info.userPassword,
            keyId: info.userPassword,
            passwordStartTime: passwordStartTime,
            passwordEndTime: passwordEndTime,
            order: 6207,
            action: 1,
            password: this.data.addpassword,
            type: 1,
            roomName: this.data.deviceinfo.roomName,
            cardName: cardName,
            operateName:_this.data.deviceinfo.name
          },
          signature:wx.getStorageSync('signature'),
        }
        console.log(dataPasswod)
        WXAPI.sendCommandOne(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()
            console.log(startTime,endTime)
            info.startTime=startTime
            info.endTime=endTime
            info.pwdNo=pwdNo
            info.password=_this.data.addpassword
            methods.bluetoothOperation_ZH(cgInfo,info,3).then(result=>{
              console.log(result)
              if (result.status == '00') {
                var datacom = {
                  code: "zg/bleSendVoucherReply",
                  signature:wx.getStorageSync('signature'),
                  cardId:deviceinfo.cardId,
                  data: {
                    lockerId: deviceinfo.deviceNum,
                    serialNumber: res.data.serialNumber,
                    index: passwordIndex,
                    type: 7,
                    result: 1,
                    operateName:_this.data.deviceinfo.name
                  }
                }
                var str = {
                  // cardId: this.personInfo.cardId,
                  imei: deviceinfo.imei,
                  pzname:pzname,
                  password: _this.data.addpassword,
                  userTelephone: info.userTelephone,
                  operateMode: 7,
                  userPassword: info.userPassword,
                  passwordStartTime: passwordStartTime,
                  passwordEndTime: passwordEndTime,
                  is: false,
                  pass:true
                }
                var data = {
                  cardId: deviceinfo.cardId,
                  content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                  deviceNum: deviceinfo.deviceNum,
                  type: 4,
                  imei: deviceinfo.imei,
                  serial: res.data.serialNumber,
                  startTime: passwordStartTime,
                  endTime: passwordEndTime,
                  signature:wx.getStorageSync('signature'),
                };
                var datalist = {
                  cardId: deviceinfo.cardId,
                  content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                  type: 14,
                  startTime: passwordStartTime,
                  endTime: passwordEndTime,
                  signature:wx.getStorageSync('signature'),
                };
                console.log(datalist,'密码11')
                WXAPI.tsAddCertificate(datalist).then(res6 => {                      
                  console.log(datalist,'密码22',res6)
                })
                console.log(data, '添加凭证')
                WXAPI.tsAddCertificate(data).then(res3 => {
                  if (res3.success) {
                    var updatedata = {
                      id: res3.data,
                      status:1,
                      signature:wx.getStorageSync('signature'),
                    };
                    WXAPI.editCertificate(updatedata).then((res2) => {
                    });
                    WXAPI.sendCommandOne(datacom).then(res2 => {
                      if (res2.success) {}
                    })
                    console.log(res3, '添加凭证成功')
                    _this.setData({
                      show: false,
                      showTwo:false
                    })
                    _this.getPassWordMehods()
                    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",
                  signature:wx.getStorageSync('signature'),
                  cardId:deviceinfo.cardId,
                  data: {
                    lockerId: deviceinfo.deviceNum,
                    serialNumber: res.data.serialNumber,
                    index: res.data.index,
                    type: 7,
                    result: 0
                  }
                }
                WXAPI.sendCommandOne(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",
            //     signature:wx.getStorageSync('signature'),
            //     data: {
            //       lockerId: deviceinfo.deviceNum,
            //       serialNumber: res.data.serialNumber,
            //       index: res.data.index,
            //       type: 7,
            //       result: 0
            //     }
            //   }
            //   WXAPI.sendCommandOne(datacom).then(res2 => {
            //     console.log(res2, '失败')
            //     _this.setData({
            //       show: false
            //     })
            //   })
            // })
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2000,
              mask:true,
              icon: 'none'
            })
          }
        })
      }
    }
  },
  closeblue() {
    app.globalData.ble.close()
    this.data.info = ''
    app.globalData.bleStatus = false
    this.data.bleStatus = false,
      this.data.respond = []
  },
  closeblue1() {
    // wx.showLoading({
    // 	title: "正在停止...",
    // });
    app.globalData.ble.close()
    // setTimeout(() => {
    // 	wx.hideLoading()
    // }, 1000);
    this.data.info = ''
    app.globalData.bleStatus = false
    this.data.bleStatus = false,
      this.data.respond = []
  },
  btntest3(event) {
    var that = this
    let deviceNum = that.data.deviceinfo.deviceNum
    this.data.backstatus = true
    that.startFp_29(deviceNum, 0x03)
    // setTimeout(() => {
    // 	that.getcartcount()
    // }, 300)
  },
  btntest2(event) {
    var that = this
    let userTelephone = "18270949468" //JSON.parse(this.data.deviceinfo.info).userTelephone
    let userPassword = "202108" //JSON.parse(this.data.deviceinfo.info).userPassword
    let pwd = "2021110309" //JSON.parse(this.data.deviceinfo.info).userPassword
    let openLockType = 2
    var userInfo=wx.getStorageSync('deviceinfo')
    var timestamp = moment().format("x")
    bleall.openLock(userTelephone, userPassword, pwd, openLockType, timestamp, function (res) {
      if (res.success) {
        var data = {
          code: "ld/bleUnlockRecord",
          signature:wx.getStorageSync('signature'),
          cardId:that.data.deviceinfo.cardId,
          data: {
            deviceNum: that.data.deviceNum,
            userTelephone: userTelephone,
            password: userPassword,
            roomId:that.data.deviceinfo.roomId,
            roomName:that.data.deviceinfo.roomName,
            cardName:userInfo.name,
          }
        }
        WXAPI.sendCommandOne(data).then(res => {

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

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

    let up = util.stringToUint8Array(userPassword)

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

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

    let b = new Uint8Array(length)

    b[0] = cmd
    b.set(ut, 1)
    b.set(up, 12)
    b.set(p, 18)
    b[28] = openLockType
    console.log(b)
    app.globalData.ble.send(cmd, b, length)
  },
  //远程开锁
  remoteUnlocking() {
    if (this.data.info == '蓝牙已连接') {
      this.closeblue1()
    }
    var str2 = {
      imei: this.data.deviceinfo.imei,
      openLockType: 2,
      is: true,
    };
    WXAPI.openLock(str2).then(res => {
      if (res.data.success) {
        wx.showToast({
          title: "操作成功",
          icon: "none",
          duration: 2000
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.globalData.zgBlueStatus = false
    // this.btntest1()
  },
  AddressPermissions() {
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log('蓝牙已开启!');
      },
      fail: function (e) {
        console.log(e)
        wx.showToast({
          title: '请打开蓝牙！',
          duration: 2000,
          icon: 'none'
        })
      }
    });
    ICINLocker.getLocationPermission().then((res) => {
      if (res.status == 0) {} else {
        // 连接出现问题
      }
    }).catch((res) => {
      //处理未能获得地理位置情况
      wx.showToast({
        title: '请打开微信定位功能!',
        duration: 2000,
        icon: 'none'
      })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var deviceinfo = wx.getStorageSync('deviceinfo')
    this.setData({
      deviceinfo:deviceinfo,
      bleStatus: app.globalData.bleStatus
    })
  },

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

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

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

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

  },

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

  }
})