// pages/selectPersonnel/selectPersonnel.js
const app = getApp()
const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var util = require('../../utils/util');
var methods = require('../../utils/methods');
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 + " ";
  clock += '00:00:00';
  return (clock);
}

function CurentTime1() {
  var now = new Date();
  var year = now.getFullYear() + 1; //年
  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 + " ";
  clock += '23:59:59';
  return (clock);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datetimerange: [CurentTime(), CurentTime1()],
    endtime: CurentTime1(),
    starttime: CurentTime(),
    searchValue:"人员",
    pageSize:20,
    pageNum:1,
    personList:[],
    deviceinfo:{},
    cgInfo:{},
    show: false,
    phone: '',
    name: '',
    deviceId:'',
    personInfo:{},
    pullUpStatus:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var deviceinfo = wx.getStorageSync('deviceinfo')
    var cgInfo = wx.getStorageSync('cgInfo')
    this.setData({
      deviceinfo: deviceinfo,
      cgInfo: cgInfo
    })
    this.getPerson()
  },
  
  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
    })
  },
  // 点击人员
  clickOnPeople(e){
    var info=e.target.dataset.item
    info['content']=JSON.parse(info.info)
    this.setData({
      personInfo:info,
      show:true
    })
  },
  getPerson(){
    var data={
      q:JSON.stringify({}),
      pageSize:this.data.pageSize,
      pageNum:this.data.pageNum
    }
    WXAPI.getlistNum(data).then(res=>{
      if(res.success){
        if(res.data.list<this.data.pageSize){
          this.setData({
            pullUpStatus:false,
            personList: res.data.list
          })
        }else{
          this.setData({
            pullUpStatus:true,
            personList: res.data.list
          })
        }
      }else{
        wx.showToast({
          title: res.msg,
          duration:2000,
          mask:true,
          icon:'none'
        })
      }
    })
  },
  // 关闭添加人员弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 获取人员
  onChange(event) {
    this.setData({
      searchValue: event.detail
    })
  },
  pullUpMethods() {
    var data2 = {
      q: JSON.stringify({
        name: this.data.searchValue
      }),
      pageSize:this.data.pageSize,
      pageNum:this.data.pageNum
    }
    WXAPI.getlistNum(data2).then(res1 => {
      if (res1.data.list.length > 0) {
        var pullUpStatus=true
        if(res1.data.list<this.data.pageSize){
          pullUpStatus=false
        }else{
          pullUpStatus=false
        }
        var list=this.data.personList.concat(res1.data.list)
        this.setData({
          pullUpStatus:pullUpStatus,
          personList: list
        })
      } else {
        wx.showToast({
          title: "未发现该人员",
          duration: 2000,
          mask:true,
          icon: 'none'
        })
      }
    })
  },
  onClick() {
    var data2 = {
      q: JSON.stringify({
        name: this.data.searchValue
      }),
      pageSize:this.data.pageSize,
      pageNum:1
    }
    WXAPI.getlistNum(data2).then(res1 => {
      if (res1.data.list.length > 0) {
        var pullUpStatus=true
        if(res1.data.list<this.data.pageSize){
          pullUpStatus=false
        }else{
          pullUpStatus=false
        }
        this.setData({
          pullUpStatus:pullUpStatus,
          personList: res1.data.list
        })
      } else {
        wx.showToast({
          title: "未发现该人员",
          duration: 2000,
          mask:true,
          icon: 'none'
        })
      }
    })
  },
  addperson(e) {
    var deviceinfo = this.data.deviceinfo
    if (deviceinfo.manufactureId == 201||deviceinfo.manufactureId == 221) {
      if (app.globalData.zgBlueStatus) {
        this.adduser()
      } else {
        this.goBlue()
      }
    } else if (deviceinfo.manufactureId == 101) {
      if (app.globalData.bleStatus == '蓝牙已连接') {
        this.adduser()
      } else {
        this.startconnect()
      }
    }
  },
  goBlue() {
    var that = this
    var cgInfo = wx.getStorageSync('cgInfo')
    wx.showLoading({
      title: '连接中',
      mask:true
    })
    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({
                  deviceId: deviceId
                })
                app.globalData.zgBlueStatus = true
                wx.hideLoading()
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  mask:true,
                  duration: 2000
                })
                this.adduser()
              } 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: "连接中",
      mask:true
    })
    var deviceinfo = this.data.deviceinfo
    const ble = new BLE(this.data.deviceinfo.deviceNum, emitter)
    app.globalData.ble = ble
    this.watchBLE()
    app.globalData.ble.init()
    // }
  },
  watchBLE() {
    var that = this
    if (app.globalData.ble) {
      app.globalData.ble.listen(res => {
        if (res.type == 'connect') {
          if (res.data == "未打开适配器") {
            wx.hideLoading()
            wx.showModal({
              title: "提示",
              content: "请检查手机蓝牙和定位功能是否打开？",
              showCancel: false,
              confirmText: "确定",
              success(res) {}
            });
          } else {
            if (res.data == '蓝牙已连接') {
              app.globalData.bleStatus = res.data
              this.adduser()        
            }
          }
        }
      })
    }
  },
  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,
        icon: 'none',
        mask:true,
      })
      return
    }
    if (this.data.personInfo.content.userTelephone == '' || this.data.personInfo.name == '') {
      wx.showToast({
        title: '请填写完整信息',
        duration: 2000,
        mask:true,
        icon: 'none'
      })
    }else if(this.data.personInfo.content.userTelephone.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 userPassword = this.data.personInfo.content.userPassword
        var data = {
          managerTelephone: "18270949468",
          managerPassword: "202108",
          userTelephone: this.data.personInfo.content.userTelephone,
          password: userPassword,
          userPassword: userPassword,
          startTime: time1,
          endTime: time2
        }
        var timestamp= moment().format("x")
        console.log(data,'-----')
        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) {
                    var data2 = [{
                      cardId: _this.data.personInfo.id,
                      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.personInfo.content.userTelephone,
                          userPassword: userPassword,
                          userStartTime: time1,
                          userEndTime: time2,
                          password: userPassword,
                          passwordStartTime: time1,
                          passwordEndTime: time2,
                          operateMode: 1,
                          order: 6226,
                          roomName:_this.data.deviceinfo.roomName,
                          cardName:'蓝牙'+_this.data.personInfo.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)
                        }
                      })
                      _this.setData({
                        show: false
                      })
                      wx.navigateBack({
                        delta: 1
                      })
                    }) 
                  }
                })
            }
            if (res.data == "蓝牙功能暂不支持") {
              wx.showLoading({
                title: '重连中',
                mask:true
              })
              _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 usrID = this.data.personInfo.content.userId
        wx.showLoading({
          title: '正在添加',
          mask:true
        })
        let info={
          usrID:usrID,
          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: usrID,
              keyId: usrID,
              role: 0,
              order: 6226,
              action: 1,
              roomName:this.data.deviceinfo.roomName,
              cardName:'蓝牙'+this.data.personInfo.name,
              type: 1,
              result: 1
            }
            var data2 = [{
              cardId: this.data.personInfo.id,
              siteId: this.data.deviceinfo.roomId,
              startTime: time1,
              endTime: time2
            }]
            WXAPI.bindCard(data2).then(res2 => {
              if (res2.success) {
                WXAPI.ZGduserOperation(dataPasswod).then(res6 => {
                  console.log(res6)
                  if (res6.success) {
                    var data3 = {
                      result: 1,
                      serial: res6.data.serialNumber
                    }
                    setTimeout(()=>{
                      WXAPI.updatePush(data3).then(res4 => {

                      })
                    },1000)                   
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加成功',
                      icon: 'none',
                      mask:true,
                      duration: 2000
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '添加失败',
                      icon: 'none',
                      mask:true,
                      duration: 2000
                    })
                  }
                })
                this.setData({
                  show: false
                })
                wx.showToast({
                  title: '绑定成功',
                  icon: 'none',
                  mask:true,
                })
                wx.navigateBack({
                  delta: 1
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '添加失败',
                  mask:true,
                  icon: 'none'
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '添加失败',
              duration: 2000,
              mask:true,
              icon: 'none'
            })
          }
        })
      }
    }
  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.pullUpStatus){
      var pageNum=this.data.pageNum+1
      this.setData({
        pageNum:pageNum
      })
      this.pullUpMethods()
    }
  },

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

  }
})