// index.js
// 获取应用实例
const app = getApp()
var util = require('../../utils/util');
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
const WXAPI = require('../../utils/request')
// 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 {
  ztreeToElementTree,
  IntToBytesLittleEndian,
  BytesToIntBigEndian,
  uniqueArray
} from "../../utils/util"
import moment from "../../utils/moment"
Page({
  data: {
    show: false,
    signKey: '',
    commonKey: '',
    list: [],
    searchValue: '',
    userInfo: {},
    pageNum: 1,
    pageSize: 20,
    stoppull: false,
    zNodes: [],
    index: 0,
    array: [],
    index1: 0,
    array1: [],
    ces: 0,
    ces1: '',
    ces2: '',
    dataList: [],
    selectKey: '', //选中的节点id
    selectRoomName: '选择房间',
    pid:'',
    treeList:[],
    allDevice:[],
    devices_list:[],
    searching:''
  },
  onLoad() {    
    this.getAllDevice()
    var userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo,
    })
    wx.getStorage({
      key: "token",
      success: (res) => {
        // this.getIntegration()
        if (userInfo.type >= 3) {
          this.getRoomList()
          this.getRoom1()
        } else if (userInfo.type < 3) {
          this.getTree()
        }
      },
      fail: (res) => {
        wx.redirectTo({
          url: "/pages/login/login"
        })
      }
    })
  },
  getCgInfo(deviceNum){
    return  new Promise((resolve, reject)=>{
      var data3 = {
        code: "zg/bleRegisterInfo",
        data: {
          lockerId: deviceNum
        }
      }
      WXAPI.sendCommand(data3).then(res1 => {
        if(res1.success){
          resolve(res1)
        }else{
          reject(res1)
        }
      })
    })
  },
  // 获取所有设备
  getAllDevice(){
    var data1={
      pageNum: 0,
      pageSize: 0,
    }    
    WXAPI.getDeviceItems(data1).then(res => {
        if(res.success){
          this.setData({
            allDevice:res.data.list
          })
        }
    })
  },
  handleSelect(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,
      show: false
    })
    this.getRoom2(e.detail.item.id)
  },
  bindroom() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  zh() {
    var time = moment().format("x")
    var str = this.toBin(time)
    console.log(str)
    var ces1 = IntToBytesLittleEndian(time, 6)
    var ces2 = BytesToIntBigEndian(ces1)
    this.setData({
      ces: time,
      ces1: ces1,
      ces2: ces2,
    })
  },
  toBin(str) {
    var arr = [];
    var remainder, i, str2, num, char;
    while (str.length > 0) {
      str2 = "";
      remainder = 0;
      for (i = 0; i < str.length; i++) { // str2 = str组成的十进制数 / 2
        num = str.charCodeAt(i) - 0x30; // num to String
        num = remainder * 10 + num;
        char = Math.floor(num / 2).toString();
        // 忽略最高为的0 ， 即最高为如果是 0 则不放入 str2
        if (!(char === "0" && str2 === "")) {
          str2 += char;
        }
        remainder = num % 2;
      }
      str = str2;
      arr.push(remainder); // 保存余数
    }
    return arr.reverse().join('');
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var array1 = [],
      children = []
    if (this.data.zNodes[e.detail.value].children) {
      children = this.data.zNodes[e.detail.value].children
      children.map(li => {
        array1.push(li.name)
      })
    }
    this.getRoom2(this.data.zNodes[e.detail.value].id)
    this.setData({
      index: e.detail.value,
      array1: array1
    })
  },
  bindPickerChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.getRoom2(this.data.zNodes[this.data.index].children[e.detail.value].id)
    this.setData({
      index1: e.detail.value,
    })
  },
  getRoomList(){    
    var data = {
      pageNum: 0,
      pageSize: 0
    };
    WXAPI.getSiteList(data).then(res => {      
      var newArr = util.uniqueArray(res.data.list.list, "id");
      this.setData({
        treeList:newArr
      })
    })
  },
  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') || dataList[0].name
      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()
    })
  },
  onChange(event) {
    this.setData({
      searchValue: event.detail
    })
  },
  godetail(e) {
    console.log(e)
    var IMEI = e.currentTarget.dataset.item
    // if (this.data.userInfo.type != 3) {
      if (IMEI.imei) {
        var q = {
          roomId: IMEI.id,
          // lockType:1,
          types:[1,21, 41],
        }
        var data1 = {
          q: JSON.stringify(q)
        }
        WXAPI.getDeviceItems(data1).then(res => {
          console.log(res);
          if (res.data.list.length > 0) {
            // wx.setStorage({
            //   key: "deviceinfo",
            //   data: res.data.list[0]
            // })
            wx.setStorageSync('deviceinfo', res.data.list[0])
            wx.navigateTo({
              url: "/pages/roomDetail/roomDetail"
            })
          } else {
            wx.showToast({
              title: "未发现此门锁信息",
              duration: 2000,
              icon: 'none'
            })
          }
        })
      } else {
        wx.showToast({
          title: "还未绑定门锁",
          duration: 2000,
          icon: 'none'
        })
      }
    // } else if (this.data.userInfo.type == 3) {
    //   wx.setStorage({
    //     key: "deviceinfo",
    //     data: this.data.list[0]
    //   })
    //   wx.navigateTo({
    //     url: "/pages/roomDetail/roomDetail"
    //   })
    // }
  },
  // 搜索
  onClick(e) {
    var userInfo = this.data.userInfo
    this.setData({
      pageNum: 1,
      pid: '',
      list: []
    })
    wx.getStorage({
      key: "token",
      success: (res) => {
        if (userInfo.type != 3) {
          this.getRoom()
        } else if (userInfo.type == 3) {
          this.getRoom1()
        }
      },
      fail: (res) => {
        wx.redirectTo({
          url: "/pages/login/login"
        })
      }
    })
  },
  // 获取用户信息
  getuserInfo() {
    WXAPI.getuserInfo('').then(res => {
      this.setData({
        userInfo: res.data,
      });
      wx.setStorageSync("userInfo", res.data)
    })
  },
  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
  },
  // 获取房间
  getRoom2(id) {
    var q = {
      ancestor: id,
      isRoom:1
    };
    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
      }
      res.data.list.list.map(li=>{        
          var name = this.findIndexArray(this.data.dataList, li.id, [])
          var path = ''
          if (name) {
            path = name.reverse().join('/')
          }
          li['path'] = path
          var device=this.data.allDevice.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']=''
          }
      })
      var alllist = res.data.list.list
      this.setData({
        list: alllist,
        stoppull,
        pageNum: 1
      })
    })
  },
  // 获取房间
  getRoom() {
    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
      }
      res.data.list.list.map(li=>{
          var name = this.findIndexArray(this.data.dataList, li.id, [])
          var path = ''
          if (name) {
            path = name.reverse().join('/')
          }
          li['path'] = path
          var device=this.data.allDevice.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']=''
          }
      })
      var alllist = this.data.list.concat(res.data.list.list)
      this.setData({
        list: alllist,
        stoppull
      })
    })
  },
  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;
  },
  // 获取房间列表
  getRoom1() {
    var q = {
      number: this.data.userInfo.username,
      isRoom:1,
      name:this.data.searchValue
    };
    var data = {
      q: JSON.stringify(q),
      pageNum: 0,
      pageSize: 0
    };
    WXAPI.getlistNum(data).then(res => {
      if(res.success){
        var person=res.data.list[0]
        var query={}
        wx.setStorageSync('info', person)
        WXAPI.onlyTenant(query).then(res2=>{
          var dataList=res2.data.list.filter(item=> item.cardId==person.id)
          let list=[]
          dataList.map(li=>{
            var obj=this.data.treeList.filter(it=>it.id===li.roomId)[0]
            if(obj){
              list.push(obj)
            }            
            var device=this.data.allDevice.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']=''
            }
          })
          this.setData({
            list:list
          })
        })
      }else{
        wx.showToast({
          icon: "none",
          duration: 2000,
          title: "未找到该人员"
        })
      }
    })
  },
  qrcodefun() {
    var that = this
    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]
        }
        console.log(res.result.indexOf('WSL'))
        var q = {
          deviceNum: deviceNum,
          // lockType:1,
          types:[1,21],
        };
        var data = {
          q: JSON.stringify(q),
          pageNum: 1,
          pageSize: 10,
        };
        WXAPI.getDeviceItems(data).then(res => {
          var len = res.data.list
          if (len.length > 0) {
            wx.setStorage({
              key: "deviceinfo",
              data: res.data.list[0]
            })
            wx.navigateTo({
              url: "/pages/roomDetail/roomDetail?open=true"
            })
          } else {
            wx.showToast({
              icon: "none",
              duration: 2000,
              title: "未在平台找到此设备！"
            })
          }
        })
      }
    })
  },
  onPullDownRefresh() {
    this.setData({      
      list:[]
    })
    this.onLoad()
    setTimeout(()=>{
      wx.stopPullDownRefresh()
    },500)
    // this.setData({
    //   pageNum: 1,
    //   list: [],
    //   stoppull: false
    // })
    // wx.getStorage({
    //   key: "token",
    //   success: (res) => {
    //     wx.stopPullDownRefresh()
    //     if (this.data.userInfo.type > 3) {
    //       this.getRoom()
    //     } else if (this.data.userInfo.type <= 3) {
    //       this.getRoom1()
    //     }
    //   },
    //   fail: (res) => {
    //     wx.stopPullDownRefresh()
    //     wx.redirectTo({
    //       url: "/pages/login/login"
    //     })
    //   }
    // })
  },
  onReachBottom() {
    var userInfo = this.data.userInfo
    if (!this.data.stoppull) {
      wx.getStorage({
        key: "token",
        success: (res) => {
          var num = this.data.pageNum + 1
          this.setData({
            pageNum: num
          })
          if (userInfo.type != 3) {
            this.getRoom()
          } else if (userInfo.type == 3) {
            this.getRoom1()
          }
        },
        fail: (res) => {
          wx.redirectTo({
            url: "/pages/login/login"
          })
        }
      })
    } else {
      wx.showToast({
        title: '暂无更多数据',
        duration: 2000,
        icon: 'none'
      })
    }
  },
  closeblue() {
    wx.showLoading({
      title: "正在停止...",
      mask: true
    });
    app.globalData.ble.close()
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);
    app.globalData.bleStatus = false
  },
  onShow: function () {
    wx.hideLoading()
    if (app.globalData.zgBlueStatus) {
      ICINLocker.disConnect(app.globalData.blueDeviceId);
    }
    if(app.globalData.bleStatus){
      this.closeblue()
    }
  },
  getUserProfile(e) {},
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onShareAppMessage() {}
})