// pages/personManger/personManger.js
const app = getApp()
const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var methods = require('../../utils/methods.js');
var md5 = require('../../utils/md5.js');
var bleall = require('../../utils/bleall');
import {
  BLE
} from "../../utils/btls/ble";
const emitter = app.globalData.emitter
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(',');
}
import moment from "../../utils/moment"

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);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datetimerange: [CurentTime(), CurentTime1()],
    endtime: '',
    starttime: '',
    personList: [],
    searchValue: '',
    deviceinfo: [],
    roomId: [],
    current: '',
    index: '',
    show: false,
    phone: '',
    name: '',
    cgInfo: {},
    number:"",
    minDate: '',
    minDate1: ''
  },

  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 + " 00:00:00"
    this.data.datetimerange[1] = str
    this.setData({
      endtime: str
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(moment().format("x"))
    var deviceinfo = wx.getStorageSync('deviceinfo')
    var cgInfo = wx.getStorageSync('cgInfo')
    if(deviceinfo.roomId){
      this.getSiteTenant(deviceinfo.roomId)
    }
    this.setData({
      deviceinfo: deviceinfo,
      roomId: deviceinfo.roomId,
      cgInfo: cgInfo
    })
  },
  onChange1(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    this.setData({
      name: event.detail
    })
  },
  onChange3(event) {
    this.setData({
      number: event.detail
    })
  },
  onChange2(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    var str = event.detail
    if (str.length > 11) {
      wx.showToast({
        title: '手机号为11位数字,请输入正确手机号',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
      str = str.substr(1, 11)
      this.setData({
        phone: str
      })
    } else {
      this.setData({
        phone: event.detail
      })
    }
  },
  // 添加用户
  adduser() {
    var _this = this
    wx.showLoading({
      title: '正在添加',
      mask:true
    })
    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
    if(passwordStartTime>passwordEndTime){
      wx.showToast({
        title: '开始时间不能大于结束时间',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
      return
    }
    if (this.data.phone == '') {
      wx.showToast({
        title: '请填写手机号',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
    }else if(this.data.name == ''){
      wx.showToast({
        title: '请填写名称',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
    }else if(this.data.number == ''){
      wx.showToast({
        title: '请填写学号',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
    }else if(this.data.phone.length !=11){
      wx.showToast({
        title: '手机号格式错误',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
    } else {
      var userInfo = wx.getStorageSync('userInfo')
      var deviceinfo = this.data.deviceinfo
      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 userPassword = JSON.stringify(this.data.phone).substring(this.data.phone.length - 6, this.data.phone.length)
        var data = {
          managerTelephone: "18270949468",
          managerPassword: "202108",
          userTelephone: this.data.phone,
          password: userPassword,
          userPassword: userPassword,
          startTime: time1,
          endTime: time2
        }
        var str = md5(this.data.phone)
        var usrID = userPassword//str.substr(str.length - 7, str.length).toUpperCase()
        var timestamp= moment().format("x")
        bleall.startFp1_63(data.managerTelephone, data.managerPassword, data.userTelephone,
          data.userPassword, data.password, data.startTime, data.endTime, 1,timestamp,
          function (res) {
            console.log(res)
            if (res.success) {
              bleall.startFp1_63(data.managerTelephone, data.managerPassword, data.userTelephone,
                data.userPassword, data.password,
                data.startTime, data.endTime, 4,timestamp,
                function (res1) {
                  if (res1.success) {
                    let loginKey = WXAPI.setCode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXKHkNKieiGOTjXZJ0lFBjhRCa\nZTaAebTIfB9nnnVmNVIp//yCfyFXSlxbAj58CQwCVhwy109ROYf3BcsQNMZz7Djo\n8a5V0JThNye4ihxLiYLawLRjb2y2/IhzV0/JZiFtaM83xUt0tbqTKxD00Up7dy8c\n9OXc0h//0uQSraf6JwIDAQAB", userPassword)
                    var infostr = {
                      userTelephone: _this.data.phone,
                      userPassword: userPassword,
                      loginKey:loginKey,
                      userId: usrID,
                      keyId: usrID,
                      pass:true
                    };
                    var data1 = {
                      cardId: _this.data.number,
                      cardState: 1,
                      info: JSON.stringify(infostr),
                      name: _this.data.name,
                      number: _this.data.number,
                      phone: _this.data.phone,
                      sex: 1,
                      type: 0,
                    };
                    WXAPI.addCard(data1).then(res => {
                      if (res.success) {
                        var data2 = [{
                          cardId: res.data,
                          siteId: _this.data.deviceinfo.roomId,
                          startTime: time3,
                          endTime: time4
                        }]
                        WXAPI.bindCard(data2).then(res2 => {
                          var data3 = {
                            code: "ble/operateUserInfo",
                            data: {
                              deviceNum: _this.data.deviceinfo.deviceNum,
                              imei: _this.data.deviceinfo.imei,
                              userTelephone: _this.data.phone,
                              userPassword: userPassword,
                              userStartTime: time1,
                              userEndTime: time2,
                              password: userPassword,
                              passwordStartTime: time1,
                              passwordEndTime: time2,
                              operateMode: 1,
                              order: 6226,
                              roomName:_this.data.deviceinfo.roomName,
                              cardName:'蓝牙'+_this.data.name,
                              timestamp: timestamp,
                              managerTelephone: '18270949468',
                              managerPassword: '202108',
                              passwordLength: 10,
                              permission: 4294967295,
                              times: 255,
                              recycleTime: "65535",
                            }
                          }
                          wx.hideLoading()
                          wx.showToast({
                            title: '添加成功',
                            icon: 'none',
                            mask:true,
                            duration: 2000
                          })
                          WXAPI.sendCommand(data3).then(res6 => {
                            if(res6.success){
                              var data4 = {
                                result: 1,
                                serial: res6.data.serialNumber
                              }
                              setTimeout(()=>{
                                WXAPI.updatePush(data4).then(res4 => {
  
                                })
                              },1000)
                            }
                            // var result='',serial=''
                            // WXAPI.editStatusBySerial('',`/v1/device/editStatus/bySerial/${result}/${serial}`).then(res2=>{

                            // })
                          })
                          _this.setData({
                            show: false
                          })
                          _this.getSiteTenant(_this.data.roomId)
                        })
                      }else{                        
                        wx.hideLoading()
                        wx.showToast({
                          title: '添加失败',
                          duration:2000,
                          icon:'none'
                        })
                      }
                    })
                  }else{
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加失败',
                      duration:2000,
                      icon:'none'
                    })
                  }
                })
            }
            if (res.data == "蓝牙功能暂不支持") {
              wx.showLoading({
                title: '重连中',
              })
              _this.startconnect()
            }
          })
      } else if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 221) {
        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 startTime = passwordStartTime.toString(16).toUpperCase()
        var endTime = passwordEndTime.toString(16).toUpperCase()
        var str = md5(this.data.phone)
        var usrID = str.substr(str.length - 7, str.length).toUpperCase()
        var userPassword = JSON.stringify(this.data.phone).substring(this.data.phone.length - 6, this.data.phone.length)
        wx.showLoading({
          title: '正在添加',
        })
        let info={
          usrID:userPassword,
          startTime:startTime, 
          endTime:endTime
        }
        methods.bluetoothOperation_ZH(this.data.cgInfo,info,1).then(result=>{
          if (result.status == '00') {
            var dataPasswod = {
              lockerId: this.data.deviceinfo.deviceNum,
              imei: this.data.deviceinfo.imei,
              lockerUserId: userPassword,
              keyId: userPassword,
              role: 0,
              order: 6226,
              action: 1,
              roomName:this.data.deviceinfo.roomName,
              cardName:'蓝牙'+this.data.name,
              type: 1,
              result: 1
            }
            let loginKey = WXAPI.setCode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXKHkNKieiGOTjXZJ0lFBjhRCa\nZTaAebTIfB9nnnVmNVIp//yCfyFXSlxbAj58CQwCVhwy109ROYf3BcsQNMZz7Djo\n8a5V0JThNye4ihxLiYLawLRjb2y2/IhzV0/JZiFtaM83xUt0tbqTKxD00Up7dy8c\n9OXc0h//0uQSraf6JwIDAQAB", userPassword)
            var infostr = {
              userTelephone: _this.data.phone,
              userPassword: userPassword,
              loginKey:loginKey,
              userId: userPassword,
              keyId: userPassword,
              pass:true
            };
            var data1 = {
              cardId: this.data.number,
              cardState: 1,
              info: JSON.stringify(infostr),
              name: this.data.name,
              number: this.data.number,
              phone: this.data.phone,
              enterpriseId: userInfo.enterpriseId,
              sex: 1,
              type: 0
            }
            WXAPI.addCard(data1).then(res => {
              if (res.success) {
                var data2 = [{
                  cardId: res.data,
                  siteId: this.data.deviceinfo.roomId,
                  startTime: time1,
                  endTime: time2
                }]
                this.setData({
                  name:'',
                  phone:'',
                  number:''
                })
                WXAPI.bindCard(data2).then(res2 => {
                  if (res2.success) {
                    WXAPI.ZGduserOperation(dataPasswod).then(res6 => {
                      console.log(res6)
                      if (res6.success) {
                        wx.hideLoading()
                        this.setData({
                          name:'',
                          phone:'',
                          number:''
                        })
                        wx.showToast({
                          title: '添加成功',
                          icon: 'none',
                          mask:true,
                          duration: 2000
                        })
                      } else {
                        wx.hideLoading()
                        wx.showToast({
                          title: '添加失败',
                          icon: 'none',
                          mask:true,
                          duration: 2000
                        })
                      }
                    })
                    this.getSiteTenant(this.data.roomId)
                    this.setData({
                      show: false
                    })
                    wx.showToast({
                      title: '绑定成功',
                      mask:true,
                      icon: 'none',
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加失败',
                      mask:true,
                      icon: 'none'
                    })
                  }
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '添加失败',
                  mask:true,
                  icon: 'none'
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '添加失败',
              mask:true,
              duration: 2000,
              icon: 'none'
            })
          }
        })
      }else if(deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241){
        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 userPassword = JSON.stringify(this.data.phone).substring(this.data.phone.length - 6, this.data.phone.length)
        var data = {
          userTelephone: this.data.phone,
          password: userPassword,
          userPassword: userPassword,
          startTime: time1,
          endTime: time2
        }
        let loginKey = WXAPI.setCode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXKHkNKieiGOTjXZJ0lFBjhRCa\nZTaAebTIfB9nnnVmNVIp//yCfyFXSlxbAj58CQwCVhwy109ROYf3BcsQNMZz7Djo\n8a5V0JThNye4ihxLiYLawLRjb2y2/IhzV0/JZiFtaM83xUt0tbqTKxD00Up7dy8c\n9OXc0h//0uQSraf6JwIDAQAB", userPassword)
        var infostr = {
          userTelephone: _this.data.phone,
          userPassword: userPassword,
          loginKey:loginKey,
          userId: userPassword,
          keyId: userPassword,
          pass:true
        };
        var data1 = {
          cardId: _this.data.number,
          cardState: 1,
          info: JSON.stringify(infostr),
          name: _this.data.name,
          number: _this.data.number,
          phone: _this.data.phone,
          sex: 1,
          type: 0,
        };
        WXAPI.addCard(data1).then(res => {
          if (res.success) {
            var data2 = [{
              cardId: res.data,
              siteId: _this.data.deviceinfo.roomId,
              startTime: time3,
              endTime: time4
            }]
            WXAPI.bindCard(data2).then(res2 => {
              if(res2.success){
                _this.setData({
                  show: false
                })
                wx.showToast({
                  title: '人员绑定成功',
                  icon: 'none',
                  duration: 2000
                })
                _this.getSiteTenant(_this.data.roomId)
              }else{
                wx.hideLoading()
                wx.showToast({
                  title: '人员绑定失败',
                  duration:2000,
                  icon:'none'
                })
              }
            })
          }else{
            wx.hideLoading()
            wx.showToast({
              title: '添加失败',
              duration:2000,
              icon:'none'
            })
          }
        })

      }
    }
  },
  // 关闭添加人员弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 获取入住人员
  getSiteTenant(roomId) {
    var data2 = {
      q: JSON.stringify({
        id: roomId
      }),
      orderBy: "createTime",
      orderType: 'desc'
    }
    WXAPI.getSiteTenant(data2).then(res1 => {
      if (res1.data.list.length > 0) {
        let minDate = res1.data.list[0].startTime
        let minDate1 = res1.data.list[0].endTime
        let starttime = moment(minDate).format('YYYY-MM-DD HH:mm:ss')
        let endtime = moment(minDate1).format('YYYY-MM-DD HH:mm:ss')
        wx.setStorageSync('minDate',starttime)
        wx.setStorageSync('minDate1',endtime)
        this.setData({
          personList: res1.data.list,
          roomId: roomId,
          starttime,
          endtime,
          minDate,minDate1
        })
      } else {
        this.setData({
          personList: []
        })
        wx.showToast({
          title: "还未下发人员，请先下发人员",
          mask:true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  onChange(event) {
    this.setData({
      searchValue: event.detail
    })
  },
  onClick(e) {
    var data2 = {
      q: JSON.stringify({
        id: this.data.roomId,
        name: this.data.searchValue
      }),
      orderBy: "createTime",
      orderType: 'desc'
    }
    WXAPI.getSiteTenant(data2).then(res1 => {
      if (res1.data.list.length > 0) {
        let minDate = res1.data.list[0].startTime
        let minDate1 = res1.data.list[0].endTime
        let starttime = moment(minDate).format('YYYY-MM-DD HH:mm:ss')
        let endtime = moment(minDate1).format('YYYY-MM-DD HH:mm:ss')
        wx.setStorageSync('minDate',starttime)
        wx.setStorageSync('minDate1',endtime)
        this.setData({
          personList: res1.data.list,
          starttime,
          endtime,
          minDate,minDate1
        })
      } else {
        wx.showToast({
          title: "未发现该人员",
          mask:true,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  //选择已存在人员
  personnelCheckin(){
    wx.navigateTo({
      url: '/pages/selectPersonnel/selectPersonnel',
    })
  }, 

  // 添加人员
  addperson(e) {
    var deviceinfo = this.data.deviceinfo
    var current = e.currentTarget.dataset.current
    this.setData({
      current: current
    })
    if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 221) {
      if (app.globalData.zgBlueStatus) {
        this.setData({
          show: true
        })
      } else {
        this.goBlue()
      }
    } else if (deviceinfo.manufactureId == 101) {
      if (app.globalData.bleStatus == '蓝牙已连接') {
        this.setData({
          show: true
        })
      } else {
        this.startconnect()
      }
    }else if (deviceinfo.manufactureId == 1201) {
      this.setData({  
        show: true
      })
    }else if (deviceinfo.manufactureId == 1241) {
      this.setData({
        show: true
      })
    }
  },
  addperson1(e) {
    wx.showLoading({
      title: '加载中...',
    })
    var deviceinfo = this.data.deviceinfo
    var that = this
    var cgInfo = wx.getStorageSync('cgInfo')
    var current = e.currentTarget.dataset.current
    var index = e.currentTarget.dataset.index
    var personLi = that.data.personList[index]
    wx.setStorageSync('personLi', that.data.personList[index])
    this.setData({
      current: current,
      index: index
    })
    // wx.navigateTo({
    //   url: '/pages/addperson/addperson?current=' + current,
    // })
    // return
    if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 201) {
      if (app.globalData.zgBlueStatus) {
        if (current == 1) {
          wx.hideLoading()
          wx.navigateTo({
            url: '/pages/addperson/addperson?current=' + current,
          })
        } else if (current == 2) {
          wx.hideLoading()
          wx.showModal({
            title: '是否删除',
            success(res) {
              if (res.confirm) {
                wx.showLoading({
                  title: '加载中...',
                })
                var info = JSON.parse(that.data.personList[that.data.index].info)
                var personLi = that.data.personList[that.data.index]
                ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
                  (callback) => {
                    if(callback.status=='00'){
                      var signKey = callback.signKey
                      ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, signKey, (callback1) => {
                        if(callback1.status=='00'){
                          var commonKey = callback1.commonKey
                          ICINLocker.deleteUser(cgInfo.lockerId, cgInfo.superId, info.userId, cgInfo.superId, '', signKey, commonKey, (callback2) => {
                            if (callback2.status == '00') {
                              var data = {
                                lockerId: deviceinfo.deviceNum,
                                imei: deviceinfo.imei,
                                lockerUserId: info.userId,
                                keyId: info.userId,
                                role: '00',
                                action: 2,
                                order: 6203,
                                type: 3,
                                result: 1,
                                cardName:personLi.name,
                                roomName:deviceinfo.roomName
                              };
                              WXAPI.ZGduserOperation(data).then(res => {
                                if(res.code==200){
                                  var data3 = {
                                    result: 1,
                                    serial: res.data.serialNumber
                                  }
                                  setTimeout(()=>{
                                    WXAPI.updatePush(data3).then(res4 => {
      
                                    })
                                  },1000)
                                }else{                                  
                                  var data3 = {
                                    result: 702,
                                    serial: res.data.serialNumber
                                  }
                                  setTimeout(()=>{
                                    WXAPI.updatePush(data3).then(res4 => {
      
                                    })
                                  },1000)
                                }
                              })
                              var str = [{
                                cardId: personLi.cardId,
                                siteId: that.data.deviceinfo.roomId,
                              }]
                              WXAPI.unbindCard(str).then(res => {
                                if (res.success) {
                                  that.getSiteTenant(that.data.roomId)
                                }
                              })
                              wx.hideLoading()
                            } else {
                              wx.hideLoading()
                              wx.showToast({
                                title: '删除失败',
                                duration: 2000,
                                mask:true,
                                icon: 'none'
                              })
                            }
                          })
                        }else{
                          wx.hideLoading()
                          wx.showToast({
                            title: '连接失败',
                            duration: 2000,
                            mask:true,
                            icon: 'none'
                          })
                        }
                      })
                    }else{
                      wx.hideLoading()
                      wx.showToast({
                        title: '连接失败',
                        duration: 2000,
                        mask:true,
                        icon: 'none'
                      })
                    }
                  })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      } else {
        wx.hideLoading()
        this.goBlue()
      }
    } else if (deviceinfo.manufactureId == 101) {
      wx.hideLoading()
      if (app.globalData.bleStatus == '蓝牙已连接') {
        if (current == 1) {
          wx.navigateTo({
            url: '/pages/addperson/addperson?current=' + current,
          })
        } else if (current == 2) {
          wx.hideLoading()
          wx.showModal({
            title: '是否删除',
            success(res) {
              if (res.confirm) {
                wx.showLoading({
                  title: '加载中...',
                })
                var info = JSON.parse(that.data.personList[that.data.index].info)
                var personLi = that.data.personList[that.data.index]
                var data1 = {
                  managerTelephone: "18270949468",
                  managerPassword: '202108',
                  userTelephone: info.userTelephone,
                  userPassword: info.userPassword,
                  password: info.userPassword,
                  startTime: "20210813010101",
                  endTime: "20680813010101"
                }
                var timestamp= moment().format("x")
                bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone,
                  data1.userPassword, data1.password, data1.startTime, data1.endTime, 3,timestamp,
                  function (res) {
                    if (res.success) {
                      var data3 = {
                        code: "ble/operateUserInfo",
                        data: {
                          deviceNum: that.data.deviceinfo.deviceNum,
                          imei: that.data.deviceinfo.imei,
                          userTelephone: info.userTelephone,
                          userPassword: info.userPassword,
                          password: info.userPassword,
                          userStartTime: '20210813010101',
                          userEndTime: '20680813010101',
                          passwordStartTime: '20210813010101',
                          passwordEndTime: '20680813010101',
                          operateMode: 3,
                          order: 6203,
                          timestamp:timestamp,
                          roomName:deviceinfo.roomName,
                          cardName:'蓝牙'+personLi.name,
                          managerTelephone: '18270949468',
                          managerPassword: '202108',
                          passwordLength: 10,
                          permission: 4294967295,
                          times: 255,
                          recycleTime: "65535",
                        }
                      }
                      WXAPI.sendCommand(data3).then(res => {
                        console.log(res)
                        if(res.success){
                          var data4 = {
                            result: 1,
                            serial: res.data.serialNumber
                          }
                          setTimeout(()=>{
                            WXAPI.updatePush(data4).then(res4 => {

                            })
                          },1000)
                          var str = [{
                            cardId: personLi.cardId,
                            siteId: that.data.deviceinfo.roomId,
                          }]
                          WXAPI.unbindCard(str).then(res => {
                            if (res.success) {
                              that.getSiteTenant(that.data.roomId)
                            }
                          })
                        }
                      })
                    }
                    if (res.data == "蓝牙功能暂不支持") {
                      wx.showLoading({
                        title: '重连中',
                      })
                      that.startconnect()
                    }
                  })
              }
            }
          })
        }
      } else {
        this.startconnect()
      }
    }else if(deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241){ 
      if (current == 1) {
        wx.navigateTo({
          url: '/pages/addperson/addperson?current=' + current,
        })
      } else if (current == 2) {
        wx.hideLoading()
        wx.showModal({
          title: '是否删除',
          success(res) {
            if (res.confirm) {
              var str = [{
                cardId: personLi.cardId,
                siteId: that.data.deviceinfo.roomId,
              }]
              WXAPI.unbindCard(str).then(res => {
                if (res.success) {
                  that.getSiteTenant(that.data.roomId)
                }
              })
            }
          }
        })
      }
    }
  },
  goBlue() {
    var that = this
    var cgInfo = wx.getStorageSync('cgInfo')
    wx.showLoading({
      title: '连接蓝牙中',
    })
    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) // 此处 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: '连接成功',
                  mask:true,
                  icon: "none",
                  duration: 2000
                })
                if (that.data.current === 0) {
                  this.setData({
                    show: true
                  })
                } else if (that.data.current == 1) {
                  wx.navigateTo({
                    url: '/pages/addperson/addperson?current=' + that.data.current,
                  })
                } else if (that.data.current == 2) {
                  var info = JSON.parse(that.data.personList[that.data.index].info)
                  var personLi = that.data.personList[that.data.index]
                  ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
                    (callback) => {
                      var signKey = callback.signKey
                      console.log(signKey, 'signKey')
                      ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, signKey, (callback) => {
                        var commonKey = callback.commonKey
                        console.log(commonKey, 'commonKey')
                        ICINLocker.deleteUser(cgInfo.lockerId, cgInfo.superId, info.userId, cgInfo.superId, '', signKey, commonKey, (callback) => {
                          console.log(callback, "删除人员")
                          if (callback.status == '00') {
                            var str = [{
                              cardId: personLi.cardId,
                              siteId: that.data.deviceinfo.roomId,
                            }]
                            console.log(str, 'str')
                            WXAPI.unbindCard(str).then(res => {
                              if (res.success) {
                                that.getSiteTenant(that.data.roomId)
                              }
                            })
                          } else {
                            wx.showToast({
                              title: '删除失败',
                              mask:true,
                              duration: 2000,
                              icon: 'none'
                            })
                          }

                        })
                      })
                    })
                }
              } else {
                wx.hideLoading()
                var msg = ''
                switch (res.errCode) {
                  case 10001:
                    msg = '调用失败，请打开蓝牙！';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  mask:true,
                  icon: 'none'
                })
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              console.log(res, '失败')
              // 此处处理未能连接成功问题
            })
        }
      })
      .catch((res) => {
        //此处处理未能连接到蓝牙的问题
        if (res.status == 1) {
          if (res.statusReason.errCode == 10001) {
            wx.hideLoading()
            wx.showModal({
              title: "提示",
              content: "请检查手机蓝牙和定位功能是否打开？",
              showCancel: false,
              confirmText: "确定",
              success(res) {}
            });
          } else {
            if (!app.globalData.zgBlueStatus) {
              that.goBlue()
            } else {
              wx.hideLoading()
            }
          }
        }
      })
  },
  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
    if (app.globalData.ble) {
      app.globalData.ble.listen(res => {
        if (res.type == 'connect') {
          if (res.data == "未打开适配器") {
            wx.hideLoading()
            wx.showModal({
              title: "提示",
              content: "请检查手机蓝牙和定位功能是否打开？",
              showCancel: false,
              confirmText: "确定",
              success(res) {}
            });
          } else {
            if (res.data == '蓝牙已连接') {
              app.globalData.bleStatus = res.data
              if (that.data.current == 0) {
                this.setData({
                  show: true
                })
              } else if (that.data.current == 1) {
                wx.navigateTo({
                  url: '/pages/addperson/addperson?current=' + that.data.current,
                })
              } else if (that.data.current == 2) {
                wx.showModal({
                  title: '是否删除',
                  success(res) {
                    if (res.confirm) {
                      wx.showLoading({
                        title: '加载中...',
                      })
                      var info = JSON.parse(that.data.personList[that.data.index].info)
                      var personLi = that.data.personList[that.data.index]
                      var data1 = {
                        managerTelephone: "18270949468",
                        managerPassword: '202108',
                        userTelephone: info.userTelephone,
                        userPassword: info.userPassword,
                        password: info.userPassword,
                        startTime: "20210813010101",
                        endTime: "20680813010101"
                      }
                      var timestamp= moment().format("x")
                      bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone,
                        data1.userPassword, data1.password, data1.startTime, data1.endTime, 3,timestamp,
                        function (res) {
                          if (res.success) {
                            var data3 = {
                              code: "ble/operateUserInfo",
                              data: {
                                deviceNum: that.data.deviceinfo.deviceNum,
                                imei: that.data.deviceinfo.imei,
                                userTelephone: info.userTelephone,
                                userPassword: info.userPassword,
                                password: info.userPassword,
                                userStartTime: '20210813010101',
                                userEndTime: '20680813010101',
                                passwordStartTime: '20210813010101',
                                passwordEndTime: '20680813010101',
                                operateMode: 3,
                                order: 6203,
                                timestamp: timestamp,
                                managerTelephone: '18270949468',
                                managerPassword: '202108',
                                passwordLength: 10,
                                permission: 4294967295,
                                times: 255,
                                recycleTime: "65535",
                              }
                            }
                            WXAPI.sendCommand(data3).then(res => {

                            })
                            var str = [{
                              cardId: personLi.cardId,
                              siteId: that.data.deviceinfo.roomId,
                            }]
                            WXAPI.unbindCard(str).then(res => {
                              if (res.success) {
                                that.getSiteTenant(that.data.roomId)
                              }
                            })
                          }
                          if (res.data == "蓝牙功能暂不支持") {
                            wx.showLoading({
                              title: '重连中',
                            })
                            that.startconnect()
                          }
                        })
                    }
                  }
                })
              }
            }
          }
        }
      })
    }
  },
  //普通用户获取 signk
  getUserSignKey(data, callback) {
    // ICINLocker.getUserSignKey(data.lockId, data.superAdminId, data.usrId, data.keyId, data.authUserSignKeyOrAuthKey, data.accessType, (callback1) => {
    //   console.log(callback1)
    //   callback(callback1)
    // })
    ICINLocker.getSignKey(data.lockId, data.usrId, data.keyId, (callback1) => {
      console.log(callback1)
      callback(callback1)
    })
  },
  // 协商通讯密钥
  getCommonKey(data, callback) {
    ICINLocker.getCommonKey(data.lockId, data.usrId, data.keyId, data.userSignKey, (callback2) => {
      console.log(callback2)
      callback(callback2)
    })
  },

  // 删除用户
  ZGdeleteUser(data, callback) {
    ICINLocker.deleteUser(data.lockId, data.superAdminId, data.usrId, data.keyId, data.delUserToken, data.signkey, data.commonKey, (callback1) => {
      console.log(callback1)
      callback(callback1)
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var deviceinfo = wx.getStorageSync('deviceinfo')
    // this.getSiteTenant(deviceinfo.roomId)
  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

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

  },

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

  },

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

  }
})