// pages/permissions/permissions.js
const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var util = require('../../utils/util');
import {
  BLE
} from "../../utils/btls/ble";
const app = getApp();
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(',');
}

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 += hh + ":";
  if (mm < 10) clock += '0';
  clock += mm;
  return (clock);
}
var date = new Date()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    personInfo: {},
    password: '',
    datetimerange: [CurentTime(), CurentTime()],
    deviceinfo: {},
    endtime: '',
    starttime: '',
    minDate: CurentTime(),
    minDate1: CurentTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userInfo1 = wx.getStorageSync('userInfo')
    if (userInfo1.type != 3) {
      this.data.personInfo = wx.getStorageSync('info')
    } else if (userInfo1.type == 3) {
      this.data.personInfo = wx.getStorageSync('deviceinfo')
    }
    this.data.deviceinfo = wx.getStorageSync('deviceinfo')
  },
  onChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      password: event.detail
    })
  },
  bindDateChange: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[0] = str
    this.setData({
      starttime: e.detail.value,
      minDate1: e.detail.value
    })
  },
  bindDateChange1: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[1] = str
    this.setData({
      endtime: e.detail.value
    })
  },
  addwordfun() {
    var _this=this
    if (this.data.deviceinfo.manufactureId == 201||this.data.deviceinfo.manufactureId == 221) {
      if (app.globalData.zgBlueStatus) {
        var deviceinfo = this.data.deviceinfo
        var info = JSON.parse(this.data.personInfo.info)
        var cgInfo = wx.getStorageSync('cgInfo')
        ICINLocker.getUserSignKey(cgInfo.lockerId, cgInfo.superId, info.userPassword, cgInfo.superId, cgInfo.authKey, '01', (callback) => {
          console.log(callback)
          if (callback.status == '00') {
            var userSignKey = callback.userSignKey
            ICINLocker.getCommonKey(cgInfo.lockerId, info.userPassword, info.userPassword, userSignKey, (callback) => {
              console.log(callback, 'commonKey')
              var commonKey = callback.commonKey
              ICINLocker.handlePwd(deviceinfo.deviceNum, cgInfo.superId, info.userPassword, this.data.password, '00', cgInfo.superId, cgInfo.authKey, '', '00000000', 'FFFFFFFF', 255, commonKey, (callback) => {
                console.log(callback.status)
                if(callback.status='00'){
                  var passwordStartTime = _this.data.datetimerange[0].replaceAll('-', '').replaceAll(':', '').replaceAll(
                    ' ',
                    '')
                  var passwordEndTime = _this.data.datetimerange[1].replaceAll('-', '').replaceAll(':', '').replaceAll(
                    ' ', '')
                  var str = {
                    // cardId: this.personInfo.cardId,
                    imei: _this.data.deviceinfo.imei,
                    password: _this.data.password,
                    userTelephone: JSON.parse(_this.data.personInfo.info).userTelephone,
                    operateMode: 7,
                    userPassword: JSON.parse(_this.data.personInfo.info).userPassword,
                    passwordStartTime: passwordStartTime,
                    passwordEndTime: passwordEndTime,
                    is: false
                  }
                  var data = {
                    cardId: _this.data.personInfo.card,
                    content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                    deviceNum: _this.data.personInfo.deviceNum,
                    type: 4,
                    imei: _this.data.deviceinfo.imei,
                    startTime: passwordStartTime,
                    endTime: passwordEndTime,
                  };
                  WXAPI.addCertificates(data).then(res => {
                    if(res.success){
                      wx.showToast({
                        title: '添加成功',
                      })
                    }
                  })
                }
              })
            })
          }
        })
      } else {
        this.goBlue()
      }
    } else {
      if (app.globalData.bleStatus == '蓝牙已连接') {
        var _this = this
        if (this.data.password.length != 6) {
          wx.showToast({
            title: "密码为6位数字",
            icon: 'none',
            duration: 2000
          })
        } else {
          var passwordStartTime = _this.data.datetimerange[0].replaceAll('-', '').replaceAll(':', '').replaceAll(
            ' ',
            '')
          var passwordEndTime = _this.data.datetimerange[1].replaceAll('-', '').replaceAll(':', '').replaceAll(
            ' ', '')
          var str = {
            // cardId: this.personInfo.cardId,
            imei: _this.data.deviceinfo.imei,
            password: _this.data.password,
            userTelephone: JSON.parse(_this.data.personInfo.info).userTelephone,
            operateMode: 7,
            userPassword: JSON.parse(_this.data.personInfo.info).userPassword,
            passwordStartTime: passwordStartTime,
            passwordEndTime: passwordEndTime,
            is: false,
          }
          var data = {
            cardId: _this.data.personInfo.card,
            content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
            deviceNum: _this.data.personInfo.deviceNum,
            type: 4,
            imei: _this.data.deviceinfo.imei,
            startTime: passwordStartTime,
            endTime: passwordEndTime,
          };
          WXAPI.addCertificates(data).then(res => {
            var data = {
              managerTelephone: "18270949468",
              managerPassword: "202108",
              userTelephone: JSON.parse(_this.data.personInfo.info).userTelephone,
              userPassword: JSON.parse(_this.data.personInfo.info).userPassword,
              startTime: passwordStartTime,
              password: _this.data.password,
              endTime: passwordEndTime
            }
            _this.startFp_63(data.managerTelephone, data.managerPassword, data.userTelephone, data
              .userPassword, data.password,
              data.startTime, data.endTime, 7)
          })
        }
      } else {
        this.startconnect()
      }
    }
  },
  goBlue() {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    ICINLocker.scanDevices(this.data.deviceinfo.deviceNum)
      .then((res) => {
        console.log(res)
        if (res.status == 0) {
          //成功找到蓝牙情况下进行锁连接
          ICINLocker.connect(res.deviceId) // 此处 deviceId 存起来，当断开连接时使用
            .then((res) => {
              if (res.status == 0) {
                this.setData({
                  bleStatus: '蓝牙已连接'
                })
                app.globalData.zgBlueStatus = true
                wx.hideLoading()
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  duration: 2000
                })
              } 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) => {
        //此处处理未能连接到蓝牙的问题
        switch (res.errCode) {
          case 10001:
            wx.showToast({
              title: '请打开蓝牙',
              duration: 2000,
              icon: 'none'
            });
            break;
            // default:this.goBlue();
        }
        this.goBlue()
      })
  },
  startconnect() {
    //if(checkWechatVersion())
    // {
    wx.showLoading({
      title: "连接中"
    })
    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 == '蓝牙已连接') {
              this.data.info = res.data
              app.globalData.bleStatus = res.data
              this.addwordfun()
            }
          }
        }
      })
    }
  },
  closeblue() {
    wx.showLoading({
      title: "正在停止...",
    });
    app.globalData.ble.close()
    this.data.info = ''
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);
    app.globalData.bleStatus = false
    this.data.bleStatus = false,
      this.data.respond = []
  },
  startFp_63(managerTelephone, managerPassword, userTelephone, userPassword, password, 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 pd = util.hexStringToBytesWithPadding(password, 10, 0xff)

    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] = 0xff;
    b[46] = 0xff;
    b[47] = 0xff;
    b[48] = 0xff;

    //密码长度 uint16
    b[49] = 0
    b[50] = 0x0a
    //密码数据
    b.set(pd, 51)

    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)
  },
  change(e) {
    this.data.single = e
    console.log('-change事件:', e);
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})