// pages/Bluetooth1/Bluetooth1.js

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

  /**
   * 页面的初始数据
   */
  data: {

    deviceInfo: {
      roomId: '',
    },
    dataTree: [],
    selectKey: '', //选中的节点id
    dataList: [],
    array: [],
    show: false,
    deviceNum: '',
    type: '1',
    cgInfo: '',
    lockStatus: "",
    userInfo: '',
    show1: false,
    actions: [{
        name: '静音',
        color: '#ee0a24'
      },
      {
        name: '低音',
        color: '#333'
      },
      {
        name: '高音',
        color: '#333'
      },
    ],
    volume: '',
    adminuserinfo: {
      enterpriseId: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var adminuserinfo = wx.getStorageSync('userInfo')
    this.setData({
      deviceNum: options.deviceNum,
      selectindex: options.selectindex,
      adminuserinfo: adminuserinfo
    })

    var data = {
      q: JSON.stringify({
        deviceNum: options.deviceNum,
        // lockType:1,
        types:[1,21],
      })
    }
    WXAPI.getDeviceItems(data).then(res => {
      if (res.data.list.length == 0) {
        wx.showToast({
          title: '该智能锁未加入平台,请先加入平台',
        })
        wx.navigateBack({
          delta: 0,
        })
        this.setData({
          deviceInfo: ''
        })
      } else {
        app.globalData.deviceNum = res.data.list[0].deviceNum
        this.setData({
          deviceInfo: res.data.list[0]
        })
      }
    })
    this.getRoom()
  },
  unbindRoom() {
    wx.showModal({
      title: '是否确认重置锁',
      success: (result) => {
        if(result.confirm){
          var data = [{
            siteId: this.data.deviceInfo.roomId,
            deviceId: this.data.deviceInfo.id,
          }, ]
          WXAPI.unbindDeviceSite(data).then(res => {
            if (res.success) {
              var deviceInfo = this.data.deviceInfo
              deviceInfo['roomId'] = ''
              deviceInfo['roomName'] = ''
              this.setData({
                deviceInfo
              })
              wx.showToast({
                title: '解绑成功',
                duration: 2000,
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '解绑失败',
                duration: 2000,
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
  // 设置音量
  setVoice() {

  },
  // 蓝牙开锁
  openTheDoor(e) {
    if (e) {
      this.setData({
        current: e.currentTarget.dataset.current
      })
    }
    var that = this
    let userTelephone = '18270949468'
    let userPassword = '202108'
    let pwd = '2021110309'
    let openLockType = 2
    var timestamp = moment().format("x")
    bleall.openLock(userTelephone, userPassword, pwd, openLockType, timestamp, function (data) {
      if (data) {
        wx.showToast({
          title: '开锁成功',
          duration: 2000,
          icon: "none"
        })
      } else {
        wx.showToast({
          title: '开锁失败',
          duration: 2000,
          icon: "none"
        })
      }
    })
  },
  // 重置门锁
  resetLock(e) {
    wx.showModal({
      title: '是否确认重置锁',
      success: (result) => {
        if (result.confirm) {
          if (e) {
            this.setData({
              current: e.currentTarget.dataset.current
            })
          }
          var data = {
            managerTelephone: '18070949468',
            managerPassword: '202108'
          }
          var timestamp = moment().format("x")
          bleall.startFp_26(data.managerTelephone, data.managerPassword, timestamp, function (data) {
            if (data) {
              wx.showToast({
                title: '重置成功',
                duration: 2000,
                icon: "none"
              })
  
              var data2 = {
                q: JSON.stringify({
                  id: this.data.deviceInfo.roomId
                })
              }
              WXAPI.getSiteTenant(data2).then(res2 => {
                console.log(res2, 'res22222')
                if (res2.success) {
                  var ids = []
                  res2.data.list.map(li => {
                    var obj = {
                      siteId: this.data.deviceInfo.roomId,
                      cardId: li.cardId,
                    }
                    ids.push(obj)
                  })
                  WXAPI.unbindCard(ids).then(res3 => {
                    if (res3.success) {
                      wx.showToast({
                        title: '退租成功',
                        duration: 2000,
                        icon: 'none'
                      })
                    } else {
                      wx.showToast({
                        title: '退租失败',
                        duration: 2000,
                        icon: 'none'
                      })
                    }
                  })
                } else {
                  wx.showToast({
                    title: '退租失败',
                    duration: 2000,
                    icon: 'none'
                  })
                }
              })
            } else {
              wx.showToast({
                title: '重置失败',
                duration: 2000,
                icon: "none"
              })
            }
          })
        }else{

        }
      },
      fail: (res) => {

      },
    })
  },
  // 获取房间
  getRoom() {
    var _this = this
    WXAPI.getTree('').then(res => {
      var newArr = util.uniqueArray(res.data, "id");
      this.list = newArr
      var setting = {
        data: {
          simpleData: {
            idKey: 'id',
            pIdKey: 'pid'
          },
          key: {
            children: 'children'
          }
        }
      }
      var dataList = this.transformTozTreeFormat(setting, newArr)
      this.setData({
        dataList: dataList
      })
    })
  },
  transformTozTreeFormat(setting, sNodes) {
    var i, l,
      key = setting.data.simpleData.idKey,
      parentKey = setting.data.simpleData.pIdKey,
      childKey = setting.data.key.children
    if (!key || key == "" || !sNodes) return [];
    var r = [];
    var tmpMap = [];
    for (i = 0, l = sNodes.length; i < l; i++) {
      tmpMap[sNodes[i][key]] = sNodes[i];
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey])
          tmpMap[sNodes[i][parentKey]][childKey] = [];
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
      } else {
        r.push(sNodes[i]);
      }
    }
    return r;
  },
  bindroom() {
    this.setData({
      show: true
    });
  },

  handleSelect(e) {
    var _this = this
    if (e.detail.tips) {
      wx.showToast({
        title: '请选择房间',
        icon: 'none'
      })
    } else {
      wx.showModal({
        title: '',
        content: '是否绑定',
        success(res) {
          if (res.confirm) {
            _this.setData({
              selectKey: e.detail.item.id,
              show: false
            })
            var data = {
              pageNum: 1,
              pageSize: 1,
              q: JSON.stringify({
                roomIds: [e.detail.item.id],
                // deviceNum:_this.data.deviceInfo.deviceNum,
                // lockType:1,
                types:[1,21],
              })
            }
            WXAPI.getDeviceItems(data).then(res => {
              if (res.data.list.length == 0) {
                var data2 = [{
                  siteId: e.detail.item.id,
                  deviceId: _this.data.deviceInfo.id,
                }]
                WXAPI.bindDeviceSite(data2).then(res2 => {
                  if (res2.success) {
                    _this.data.deviceInfo['roomId'] = e.detail.item.id
                    var deviceInfo = _this.data.deviceInfo
                    deviceInfo['roomId'] = e.detail.item.id
                    deviceInfo['roomName'] = e.detail.item.name
                    _this.setData({
                      deviceInfo
                    })
                    wx.showToast({
                      title: '绑定房间成功',
                      icon: 'none'
                    })
                    // _this.addAdmin()
                  } else {
                    wx.showToast({
                      title: '绑定房间失败',
                      icon: 'none'
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: '该房间已绑定',
                  icon: 'none'
                })
              }
            })
          } else if (res.cancel) {
            _this.setData({
              selectKey: e.detail.item.id,
              show: false
            })
          }
        }
      })
    }
  },
  addAdmin(e) {
    wx.showModal({
      title: '是否确认初始化管理员',
      success: (result) => {
        if (result.confirm) {
          if (e) {
            this.setData({
              current: e.currentTarget.dataset.current
            })
          }
          var _this = this
          var data = {
            deviceNum: this.data.deviceNum,
            managerTelephone: '18270949468',
            managerPassword: '680000',
            newPassword: '202108',
            key: '1234567890'
          }
          var timestamp = moment().format("x")
          bleall.startFp_23(data.deviceNum, data.managerTelephone, data.managerPassword, data.newPassword, data.key, timestamp, function (data) {
            console.log(data)
            if (data.success) {
              var data1 = {
                managerTelephone: "18270949468",
                managerPassword: '202108',
                userTelephone: '18270949468',
                userPassword: '202108',
                password: '2021110309',
                startTime: "20210813010101",
                endTime: "20680813010101"
              }
              bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone, data1
                .userPassword, data1.password,
                data1.startTime, data1.endTime, 4, timestamp,
                function (res) {
                  if (res.success) {
                    bleall.startFp1_63(data1.managerTelephone, data1.managerPassword, data1.userTelephone, data1
                      .userPassword, data1.password,
                      data1.startTime, data1.endTime, 7, timestamp,
                      function (res1) {
                        console.log(res1)
                        if (res1.success) {
                          var data2 = {
                            code: "ble/registerManager",
                            data: {
                              deviceNum: _this.data.deviceInfo.deviceNum,
                              imei: _this.data.deviceInfo.imei,
                              order: 6101,
                              telephone: '18270949468',
                              originPassword: "680000",
                              newPassword: "202108",
                              key: '1234567890',
                              status:1,
                              timestamp: timestamp
                            }
                          }
                          WXAPI.sendCommand(data2).then(res2 => {
                            console.log(res2)
                            if (res2.success) {
      
                            }
                          })
                          wx.showToast({
                            title: '初始化管理员成功',
                            duration: 2000,
                            icon: "none"
                          })
                        }
                        if (res1.data == "蓝牙功能暂不支持") {
                          wx.showLoading({
                            title: '重连中',
                            mask: true
                          })
                          _this.startconnect()
                        }
                      })
                  }
                })
            }
            if (data.data == "蓝牙功能暂不支持") {
              wx.showLoading({
                title: '重连中',
                mask: true
              })
              _this.startconnect()
            }
          })
        }
      }
    })
  },
  startconnect() {
    wx.showLoading({
      title: "连接中",
      mask: true
    })
    const ble = new BLE(this.data.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 (this.data.current == "0") {
                this.openTheDoor()
              } else if (this.data.current == "1") {
                this.addAdmin()
              } else if (this.data.current == "2") {
                this.resetLock()
              }
            }
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})