// pages/bindLock/bindLock.js
var util = require('../../utils/util');
var util1 = require('../../utils/util1');
import {
  BLE
} from "../../utils/btls/ble";
const app = getApp();
const WXAPI = require('../../utils/request')
import ICINLocker from '../../utils/ICINPakage/ICINLocker'
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 promisify(fn, args) {
  return new Promise((resolve, reject) => {
      fn({
          ...(args || {}),
          success: (res) => resolve(res),
          fail: (err) => reject(err),
      });
  });
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceNum: '',
    radio: '1',
    zgBlueStatus: false,
    bluestatus: true,
    selectindex: 1,
    info: '',
    deviceList:[],
    searchClick:false,
    show:false,
    showSelect:false,
    searchValue:'',
    pageNum: 1,
    pageSize: 20,
    zNodes: [],
    selectRoomName:'选择房间',
    allDevice:[],
    list:[],
    setRoomArr:[],
    confirmSelectKey:'',
    stoppull:false
  },
  onChange1(event) {
    this.setData({
      deviceNum: event.detail,
    });
  },
  onChange2(event) {
    this.setData({
      radio: event.detail,
    });
  },
  // 关闭弹窗
  onClose() {
    this.setData({ show: false });
  },
  onClose1() {
    this.setData({ showSelect: false });
  },
  // 打开弹窗
  selectRoom(){
    this.setData({ show: true });
  },
  // 房源搜索
  onClick() {
    this.getRoom2()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // app.globalData.zgBlueStatus = false
    let _this=this
    this.setData({
      selectindex: options.id
    })
    ICINLocker.checkTheWechatVersion()
    this.getTree()
  },
  // 触底触发
  bottomingOut(){
    if (!this.data.stoppull) {
      var num = this.data.pageNum + 1
      this.setData({
        pageNum: num
      })
      this.getRoom()
    }
  },
  // 搜索值
  onChangeSearch(event){
    this.setData({
      searchValue: event.detail
    })
  },
  //选择房源弹窗
  bindroom() {
    this.setData({
      showSelect: true
    });
  },
  // 获取所有设备
  getAllDeviceSelect(ids,callback){
    var data = {
      q: JSON.stringify({
        roomIds: ids
      })
    }
    WXAPI.getDeviceItems(data).then(res => {
      if(res.data.list.length>0){
        callback(res.data.list)
      }else{
        callback([])
      }
    }).catch(err=>{
      callback([])
    })
  },
  getTree() {
    var _this = this
    WXAPI.getTree('').then(res => {
      var list=res.data.sort((pre, cur)=>pre.id - cur.id)
      var newArr = util.uniqueArray(list, "id");
      var setting = {
        data: {
          simpleData: {
            idKey: 'id',
            pIdKey: 'pid'
          },
          key: {
            children: 'children'
          }
        }
      }
      var dataList = this.transformTozTreeFormat(setting, newArr)      
      var selectKey = wx.getStorageSync('selectKey') || ''
      var selectRoomName = wx.getStorageSync('selectRoomName') || ''
      var pid = wx.getStorageSync('pid') || dataList[0].pid
      this.setData({
        dataList: dataList,
        // pid:dataList[0].pid,
        treeList:newArr,
        // selectRoomName:dataList[0].name,
        selectKey,selectRoomName,pid
      })       
      this.getRoom()
    })
  },
  // 确认选择房间
  selectRoomId(e){
    this.setData({
      confirmSelectKey:e.currentTarget.dataset.select.id,
      show:false,
      selectRoomName:e.currentTarget.dataset.select.path
    })
  },
  handleSelect(e) {
    console.log(e)
    wx.showToast({
      title: `已选择${e.detail.item.name}`,
      icon: 'none',
      duration: 1000
    })
    wx.setStorageSync('selectKey', e.detail.item.id)
    wx.setStorageSync('selectRoomName', e.detail.item.name)
    wx.setStorageSync('pid', e.detail.item.id)
    this.setData({
      selectKey: e.detail.item.id,
      selectRoomName: e.detail.item.name,
      pid:e.detail.item.id,
      showSelect: false
    })
    this.getRoom2()
  },
  // 获取房间
  getRoom2() {
    var that = this
    var q = {
      ancestor: this.data.selectKey,
      isRoom:1,
      name:this.data.searchValue
    };
    console.log(q)
    var data = {
      q: JSON.stringify(q),
      pageNum: 1,
      pageSize: 20
    };
    WXAPI.getSiteList(data).then(res => {
      var stoppull = false
      if (res.data.list.list.length < 20) {
        stoppull = true
      }
      let setArr = []      
      var alllist = res.data.list.list
      alllist.map(lt=>{
        setArr.push(lt.id)
      })
      this.getAllDeviceSelect(setArr,function(data){
          alllist.map(li=>{
            var name = that.findIndexArray(that.data.dataList, li.id, [])
            var path = ''
            if (name) {
              path = name.reverse().join('/')
            }
            li['path'] = path
            var device=data.filter(item=>item.roomId==li.id)[0]
            if(device){
              li.deviceNum=device.deviceNum
              li['battery']=device.battery
              li['rssi']=device.rssi
              li['isOnline']=device.isOnline
              li['manufactureId']=device.manufactureId
            }else{
              li['battery']=''
              li['rssi']=''
              li['isOnline']=''
              li['manufactureId']=''
            }
        })
        that.setData({
          list: alllist,
          stoppull,
          pageNum: 1
        })
      })
    })
  },
  findIndexArray(data,id,indexArray){
      let arr = Array.from(indexArray);
        for(let i=0,len=data.length;i<len;i++){
          arr.push(data[i].name);
          if(data[i].id===id){
            return arr
          }
          let children=data[i].children;
          if(children&&children.length){
            let result=this.findIndexArray(children,id,arr);
            if(result) return result
          }
          arr.pop()
        }
        return false
  },
  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;
  },
  // 获取房间
  getRoom() {
    var that= this
    var q = {
      ancestor: this.data.pid,
      isRoom:1,
      name:this.data.searchValue
    };
    var data = {
      q: JSON.stringify(q),
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    };
    WXAPI.getSiteList(data).then(res => {
      var stoppull = false
      if (res.data.list.list.length < 20) {
        stoppull = true
      }
      let setArr = []      
      var alllist = this.data.list.concat(res.data.list.list)
      alllist.map(lt=>{
        setArr.push(lt.id)
      })
      this.getAllDeviceSelect(setArr,function(data){
          alllist.map(li=>{
            var name = that.findIndexArray(that.data.dataList, li.id, [])
            var path = ''
            if (name) {
              path = name.reverse().join('/')
            }
            li['path'] = path
            var device=data.filter(item=>item.roomId==li.id)[0]
            if(device){
              li.deviceNum=device.deviceNum
              li['battery']=device.battery
              li['rssi']=device.rssi
              li['isOnline']=device.isOnline
              li['manufactureId']=device.manufactureId
            }else{
              li['battery']=''
              li['rssi']=''
              li['isOnline']=''
              li['manufactureId']=''
            }
        })
        that.setData({
          list: alllist,
          setRoomArr:setArr,
          stoppull
        })
      })
    })
  },
  getAllDevice(deviceNum,callback){
    var data = {
      q: JSON.stringify({
        deviceNum: deviceNum
      })
    }
    WXAPI.getDeviceItems(data).then(res => {
      if(res.data.list.length>0){
        callback(res.data.list)
      }else{
        callback([])
      }
    }).catch(err=>{
      callback([])
    })
  },
  searchDevicesMethods(){
    var that = this;
    wx.showLoading({
      title: '正在搜索',
      // mask: true
    })
    this.setData({
      searchClick:false
    })
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.startBluetoothDevicesDiscovery({
          success: function (res) {
            wx.getBluetoothDevices({
              success: function (res) {
                wx.hideLoading()
                if(that.data.selectindex==1){
                  var deviceList=[]
                  res.devices.map(li=>{
                    var status=li.name.indexOf('yxwl')
                    if(status!=-1){
                      that.getAllDevice(li.name,function(data){
                        if(data.length>0){
                          li.roomName = data[0].roomName
                          deviceList.push(li)
                        }else{
                          li.roomName = ''
                          deviceList.push(li)
                        }
                      })
                    }
                  })
                  setTimeout(()=>{
                    that.setData({
                      deviceList
                    })
                  },1000)
                }else if(that.data.selectindex==2||that.data.selectindex==3){
                  var deviceList=[]
                  res.devices.map(li=>{
                    var status=li.name.indexOf('ICIN_')
                    if(status!=-1){
                      that.getAllDevice(li.name,function(data){
                        if(data.length>0){
                          li.roomName = data[0].roomName
                          deviceList.push(li)
                        }else{
                          li.roomName = ''
                          deviceList.push(li)
                        }
                      })
                      deviceList.push(li)
                    }
                  })
                  setTimeout(()=>{
                    that.setData({
                      deviceList
                    })
                  },1000)
                }else if(that.data.selectindex==4){
                  var deviceList=[]
                  console.log(res);
                  res.devices.map(it=>{
                    console.log(it);
                    var status=it.name.indexOf('WSL_')
                    if(status!=-1){
                    if (it.RSSI != 127) {
                      if (it.advertisData != null) {
                        it.adData = util1.ab2hex(it.advertisData)
                        if (it.adData.length > 10) {
                          var macStr = it.adData.substring(4, 16).toUpperCase()
                          //console.log('macStr', macStr)
                          it.mac = macStr.substr(10, 2) + ':' + macStr.substr(8, 2) + ':' + macStr.substr(6, 2) + ':' + macStr.substr(4, 2) + ':' + macStr.substr(2, 2) + ':' + macStr.substr(0, 2)
                          if (it.adData.substring(1, 2) == '1') {
                            it.isLightOn = true
                            it.textColor = 'green'
                          } else {
                            it.isLightOn = false
                            it.textColor = 'black'
                          }
                          if (it.adData.substring(3, 4) == '1') {
                            it.textColor = 'pink'
                            it.isBind = true
                          } else {
                            it.isBind = false
                          }    
                          // deviceList.push(it)
                          //console.log(it)
                        }
                      } else {
                        it.textColor = 'black'
                      }
                      console.log(it)
                      var lockModel = util1.getLockModel(it.name)
                      it.lockType = util1.getLockType(lockModel)
                      if(that.data.searchClick){                        
                        wx.navigateTo({
                          url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + it.name + '&selectindex=' + that.data.selectindex+'&connectedDeviceId='+ it.deviceId+'&name='+ it.name+'&mac=' + it.mac,
                        })
                      }else{
                        deviceList.push(it)
                      }
                      app.addDeviceWithDevName(it.name, it)
                    }
                    }
                  })
                  that.setData({
                    deviceList
                  })
                }
                console.log(res)
              }
            })
          },
          fail:function(res){
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '请重新搜索设备',
                  duration:2000,
                  icon:'none'
                })
              },
            })
          }
        })
      },
      fail: function (res) {
        console.log('请打开蓝牙和定位功能')
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '请打开蓝牙和定位功能',
              duration:2000,
              icon:'none'
            })
          },
        })
      }
    })
  },
  searchBlueButton(e) {
    var deviceId=e.currentTarget.dataset.select.name
    this.setData({
      deviceNum:deviceId
    })
    this.linkBule()
  },
  // 扫描
  scanning() {
    var that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    wx.scanCode({
      success(res) {
        var deviceNum = ''
        if (res.result.indexOf('&') != -1) {
          deviceNum = res.result.split('&')[0]
        }else if(res.result.indexOf('WSL') != -1){
          deviceNum = res.result
        }else if (res.result.indexOf('_')) {
          deviceNum = "ICIN_" + res.result.split('_')[0]
        }
        that.setData({
          deviceNum: deviceNum,
          bluestatus: true
        })
        wx.hideLoading()
      },
      fail(res) {
        wx.hideLoading()
      }
    })
  },
  linkBule() {
    wx.stopBluetoothDevicesDiscovery()
    wx.closeBluetoothAdapter()
    if (this.data.deviceNum == '') {
      wx.hideLoading()
      wx.showToast({
        title: '请输入锁号',
        duration: 2000,
        icon: 'none'
      })
    } else {
      // wx.navigateTo({
      //   url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
      // })
      // return
      if (this.data.selectindex == 1) {
        // wx.navigateTo({
        //   url: '/pages/Bluetooth1/Bluetooth1?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
        // })
        // return
        this.startconnect()
      }else if( this.data.selectindex == 4){
        this.searchDevicesMethods()
        this.setData({
          searchClick:true
        })
      } else if (this.data.selectindex == 2||this.data.selectindex == 3) {
        // wx.navigateTo({
        //   url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
        // })
        // return
        this.goBlue()
      }
    }
  },

  ConnectTo: function(e) {
    var that = this
    console.log('ConnectTo', e.currentTarget.dataset.select)
    var bleDevice = app.getDeviceByDevName(e.currentTarget.dataset.select)
    console.log('bleDevice', bleDevice)
    // wx.navigateTo({
    //   url: '../lockFun/lockFun?connectedDeviceId=' + bleDevice.deviceId + '&name=' + bleDevice.name + '&mac=' + bleDevice.mac
    // })
    wx.navigateTo({
      url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + bleDevice.name + '&selectindex=' + this.data.selectindex+'&connectedDeviceId='+ bleDevice.deviceId+'&name='+ bleDevice.name+'&mac=' + bleDevice.mac,
    })
    return
  },
  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 == '蓝牙已连接') {
              this.data.info = res.data
              app.globalData.bleStatus = res.data
              wx.navigateTo({
                url: '/pages/Bluetooth1/Bluetooth1?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
              })

            }
          }
        }
      })
    }
  },
  goBlue() {
    var that = this
    wx.showLoading({
      title: '连接中',
      // mask: true
    })
    wx.removeStorageSync("connectedDeviceId")
    ICINLocker.scanDevices(this.data.deviceNum)
      .then((res) => {
        console.log(res)
        if (res.status == 0) {
          //成功找到蓝牙情况下进行锁连接        
          app.globalData.blueDeviceId = res.deviceId
          console.log(app.globalData.blueDeviceId, 'blueDeviceId')
          ICINLocker.connect(res.deviceId, false) // 此处 deviceId 存起来,当断开连接时使用
            .then((res) => {
              if (res.status === 0) {
                wx.hideLoading()
                if(this.data.confirmSelectKey){
                  wx.navigateTo({
                    url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&type=' + this.data.radio+'&selectindex=' + this.data.selectindex+'&selectKey='+this.data.confirmSelectKey+'&selectRoomName='+this.data.selectRoomName,
                  })
                }else{
                  wx.navigateTo({
                    url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&type=' + this.data.radio+'&selectindex=' + this.data.selectindex,
                  })
                }
                //此处成功连接锁
                wx.showToast({
                  title: res.statusReason,
                  duration: 1000,
                  icon: 'none'
                })
              } else {
                var msg = ''
                switch (res.errCode) {
                  case 10001:
                    msg = '调用失败,请打开蓝牙!';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  icon: 'none'
                })
                //此处处理返回值不为成功(0)的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              wx.showToast({
                title: '连接错误',
                duration: 2000,
                icon: 'none'
              })
              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.data.bluestatus) {
              that.goBlue()
            } else {
              wx.hideLoading()
            }
          }
        }
      })
  },
  onChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      deviceNum: event.detail
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.globalData.zgBlueStatus = false
  },

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

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      bluestatus: false
    })
  },

  closeblue() {
    app.globalData.ble.close()
    app.globalData.bleStatus = false
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.closeblue()
  },

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

  },

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

  },

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

  }
})