// pages/addBlueButton/addBlueButton.js
const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var util = require('../../utils/util');
import moment from "../../utils/moment"
const app = getApp();
const CurentTime=moment().format("YYYY-MM-DD HH:mm:ss")
const CurentTime1=moment().add(60, "years").format("YYYY-MM-DD HH:mm:ss");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:true,
    deviceList:[],
    personList:[],
    timer:null,
    blueKeyId:"",
    personli:{},
    selectName:'',
    signKey:'',
    starttime:"",
    minDate:"",
    minDate1:"",
    endtime:"",
    datetimerange:[CurentTime, CurentTime1],
    minDate: CurentTime,
    minDate1: CurentTime,
    endtime: CurentTime1,
    starttime: CurentTime,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // let timer=setInterval(()=>{
      this.linkBlue()
    // },5000)
    var deviceinfo=wx.getStorageSync('deviceinfo')
    // var personli=wx.getStorageSync('personli')
    this.getSiteTenant(deviceinfo.roomId)
    this.setData({
      deviceinfo,
      // personli,
      // timer
    })
  },
  bindDateChange: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[0] = str
    this.setData({
      starttime: str,
      minDate1: str
    })
  },
  bindDateChange1: function (e) {
    var str = e.detail.value + " 23:59:59"
    this.data.datetimerange[1] = str
    this.setData({
      endtime: str
    })
  },
  btntest1(e){
    var personli=e.currentTarget.dataset.personli
    this.setData({
      personli:personli
    })
    if (app.globalData.zgBlueStatus) {
      this.addUser()
    } else {
      this.goBlue()              
    }
  },
  setDeviceKeyId(){
    var info=JSON.parse(this.data.personli.info)
    var cgInfo=wx.getStorageSync('cgInfo')
    var comm=this.stringToHex(this.data.selectName)
    var keyId="0o01weit9ti9ti"
    var password="3030000000000000000000000000000000000000"
    var infoKeyId=info.keyId?info.keyId:info.userPassword
    ICINLocker.connect(this.data.deviceId,true).then((res) => {
      if (res.status == 0) {              
        console.log(res,'蓝牙扣连接')
        ICINLocker.readBluetoothBuckle(cgInfo.lockerId, comm, callback2 => {
          if(callback2.status==0){
            console.log(infoKeyId, this.data.selectName, keyId, password, "", this.data.signKey, comm,'--------蓝牙扣')
            ICINLocker.registeBluetoothBuckle(infoKeyId, this.data.selectName, keyId, password, "", this.data.signKey, comm, callback3 => {
              if(callback3.status==0){
                wx.hideLoading()        
                ICINLocker.disConnect(this.data.deviceId).then(res=>{
                  console.log(res)
                  wx.removeStorageSync("connectedDeviceId");
                })
                this.setData({
                  show:false
                })
                wx.showToast({
                  title: '添加成功',
                  duration:2000,
                  icon:"none"
                })
              }else{        
                ICINLocker.disConnect(this.data.deviceId).then(res=>{
                  console.log(res)
                  wx.removeStorageSync("connectedDeviceId");
                })
                wx.hideLoading()
                this.setData({
                  show:false
                })
                wx.showToast({
                  title: '添加成功',
                  duration:2000,
                  icon:"none"
                })
              }
            })
          }else{            
            ICINLocker.disConnect(this.data.deviceId).then(res=>{
              console.log(res)
              wx.removeStorageSync("connectedDeviceId");
            })
            wx.hideLoading()
            wx.showToast({
              title: '读取失败',
              duration:2000,
              icon:"none"
            })
          }
        });
      }
    })
  },
  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;    
　　},
  addUser(){
    console.log("添加蓝牙扣用户")
    wx.showLoading({
      title: '添加中'
    })
    var that=this
    var cgInfo=wx.getStorageSync('cgInfo')
    var personli=this.data.personli
    var info=JSON.parse(personli.info)
    console.log("添加蓝牙扣用户",personli,cgInfo)
    var infoKeyId=info.keyId?info.keyId:info.userPassword
    ICINLocker.getUserSignKey(cgInfo.lockerId, cgInfo.superId, infoKeyId, cgInfo.superId,cgInfo.authKey,"01",
      (callback) => {
        console.log(callback,'callbackcallbackcallbackcallback')
        if (callback.status == '00') {
          ICINLocker.getCommonKey(cgInfo.lockerId,  infoKeyId,  infoKeyId, callback.userSignKey, (callback1) => {
            if (callback1.status == '00') {
              var startTime=parseInt(moment(this.data.datetimerange[0]).format("X")).toString(16).toUpperCase()
              var endTime=parseInt(moment(this.data.datetimerange[1]).format("X")).toString(16).toUpperCase()
              console.log(cgInfo.lockerId,  infoKeyId, this.data.blueKeyId, "0o01weit9ti9ti", "00", callback.userSignKey, "", callback1.commonKey, startTime, endTime)
              ICINLocker.addUserToLock(cgInfo.lockerId, infoKeyId, this.data.blueKeyId, "0o01weit9ti9ti", "00", callback.userSignKey, "", callback1.commonKey, startTime, endTime, (callback2) => {
                console.log(callback2)
                if(callback2.status=='00'){
                      this.setData({
                        signKey:callback.userSignKey
                      })
                      wx.closeBLEConnection({
                        deviceId:app.globalData.blueDeviceId,
                        success (res) {
                          app.globalData.zgBlueStatus=false
                          that.setDeviceKeyId()
                        }
                      })
                      var str = {
                        username: personli.name,
                        deviceNum:this.data.deviceinfo.deviceNum,
                        imei:this.data.deviceinfo.imei,
                        iotId:infoKeyId,
                        manufactureId:this.data.deviceinfo.manufactureId,
                        userPassword: info.userPassword,
                        roomName:this.data.deviceinfo.roomName,
                        password: "0o01weit9ti9ti",
                        passwordStartTime: moment(this.data.datetimerange[0]).format("X"),
                        passwordEndTime: moment(this.data.datetimerange[1]).format("X"),
                        operateMode: 26,
                        order: 6326
                      };
                      var dataCerti={
                        cardId: personli.cardId,
                        content: JSON.stringify(str),
                        type: 36,
                        startTime: moment(this.data.datetimerange[0]).format("X"),
                        endTime: moment(this.data.datetimerange[1]).format("X"),
                      }
                      console.log(dataCerti,"蓝牙扣添加蓝牙扣用户凭证")
                      WXAPI.addCertificates(dataCerti).then(res=>{
                        if(res.code==200){
                          var dataPasswod = {
                            lockerId: this.data.deviceinfo.deviceNum,
                            imei: this.data.deviceinfo.imei,
                            lockerUserId: infoKeyId,
                            keyId: infoKeyId,
                            role: 0,
                            order: 6226,
                            action: 1,
                            roomName:this.data.deviceinfo.roomName,
                            cardName:'蓝牙扣'+personli.name,
                            type: 1,
                            result: 1
                          }
                          WXAPI.ZGduserOperation(dataPasswod).then(res6 => {
                            console.log(res6,"上报添加蓝牙扣用户")
                          })    
                        }
                      })
                    // ICINLocker.disConnect(app.globalData.blueDeviceId).then(res=>{
                    //   if(res.status=='00'){
                    //     app.globalData.zgBlueStatus=false
                    //     that.setDeviceKeyId()
                    //   }
                    // })
                }
              })
            }
          })
        }
      })
  },
linkBlue(){
  var that=this;
  ICINLocker.searchDevices().then(res=>{
    if (res.status == 0) {
      this.setData({
        deviceList:res.deviceList
      })
    }
  }).catch((res) => {
    if (res.status == 1) {
      if (res.statusReason.errCode == 10001) {
        wx.showToast({
          title: '请检查手机蓝牙和定位功能是否打开？',
          duration: 2000,
          icon: 'none'
        })
      } else {
        if (!app.globalData.zgBlueStatus && that.data.bluestatus) {
          that.linkBlue()
        }
      }
    }
  })
},
  searchBlueButton(e) {
    var that = this
    var cgInfo=wx.getStorageSync('cgInfo')
    var comm=this.stringToHex(e.currentTarget.dataset.select.name)
    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
    if(this.data.datetimerange[0]==''||this.data.datetimerange[1]==''){
      wx.showToast({
        title: '请选择开始结束时间',
        duration:2000,
        icon:"none"
      })
    }else{
      this.setData({
        bleStatus: '蓝牙已连接',
        deviceId: deviceId,
        blueKeyId:blueKeyId,
        show:false,
        selectName:e.currentTarget.dataset.select.name
      })
      app.globalData.zgBlueStatus = 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) {
        this.setData({
          personList: res1.data.list,
          roomId: roomId
        })
      } else {
        this.setData({
          personList: []
        })
        wx.showToast({
          title: "还未下发人员，请先下发人员",
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },
  goBlue() {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    var deviceinfo=wx.getStorageSync('deviceinfo')
    ICINLocker.scanDevices(deviceinfo.deviceNum,false).then((res) => {
        if (res.status == 0) {
          var deviceId = res.deviceId
          //成功找到蓝牙情况下进行锁连接
          app.globalData.blueDeviceId = res.deviceId
          ICINLocker.connect(res.deviceId,false).then(res1 => {
              if (res1.status == "0") {
                console.log(res1)
                that.addUser()
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  duration: 2000
                })
                app.globalData.zgBlueStatus = true
                that.setData({
                  bleStatus: '蓝牙已连接',
                })
              } else {
                wx.hideLoading()
                var msg = ''
                switch (res1.errCode) {
                  case 10001:
                    msg = '调用失败，请打开蓝牙！';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  icon: 'none'
                })
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              // 此处处理未能连接成功问题
            })
        }
      })
      .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()
            }
          }
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})