<template>
<view :class="$isEmpty(scanList)?'empty-wrap':''">
<view class="container" v-if="scanList.length>0">
  <scroll-view scroll-y :style="'height:' + list_height + 'rpx'">
    <block v-for="(item, index) in scanList" :key="index">
      <view class="list-item">
        <view style="display:flex;flex-direction:column;width:80%">
          <text style="font-size:medium;word-break:break-all">设备名称: {{item.name}}</text>
          <text style="font-size:x-small;color:gray;word-break:break-all">设备ID: {{item.deviceId}}</text>
          <text style="font-size:x-small;color:gray;word-break:break-all">信号强度RSSI: {{item.RSSI}}</text>
        </view>
        <view class="openBtn" :data-deviceId="item.deviceId" :data-wxapp_ekey="item.wxapp_ekey" @tap="openDoor">开门</view>
      </view>
    </block>
  </scroll-view>
</view>
<view class="default" v-if="scanList==null || scanList.length==0">
  <image src="/static/common/empty.png" mode="heightFix"></image>
  <view>
    <text>没有扫描到设备</text>
  </view>
</view>
</view>
</template>

<script>
//西墨sdk对象
var tmsdk = require("assets/js/DoormasterSDK-V1.4.js");
const app = getApp();
export default {
  data() {
    return {
      scanList: null
    };
  },

  components: {},
  props: {},

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    //监听蓝牙适配器状态变化
    uni.onBluetoothAdapterStateChange(function (res) {//console.log(`----adapterState changed, now is`, res)
    }); //扫描附近设备

    this.scanDevices();
  },

  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    uni.stopPullDownRefresh(); //注意！下拉刷新，Android系统设备应执行一次停止蓝牙发现接口

    if (app.globalData.platform == 'android') {
      uni.stopBluetoothDevicesDiscovery({
        success: function (res) {// console.log('----stopBluetoothDevicesDiscovery', res)
        }
      });
    } //重新扫描蓝牙设备


    this.scanDevices();
  },
  onUnload: function () {
    uni.stopBluetoothDevicesDiscovery({
      success: function (res) {// console.log('---stopBluetoothDevicesDiscovery--success',res);
      }
    });
    uni.closeBluetoothAdapter({
      success: function (res) {// console.log('---closeBluetoothAdapter--success', res);
      }
    });
  },
  methods: {
    //扫描蓝牙设备
    scanDevices: function () {
      uni.showLoading({
        title: '扫描中...',
        mask: true
      });
      var that = this;
      tmsdk.scanDevices(function (res) {
        if (!res.isBluetoothAvailable) {
          uni.hideLoading();
          uni.showModal({
            content: '请打开蓝牙',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1 // 返回上一级页面。

                }); //跳转到首页
                // wx.redirectTo({
                //   url: '/pages/index/index'
                // })
              }
            }
          });
          return;
        } //筛选后的西墨设备列表


        var scanList = res.scanList; //未获取的设备

        if (scanList.length == 0) {
          uni.hideLoading();
          uni.showModal({
            content: '未获取到设备信息，请靠近设备再试',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1 // 返回上一级页面。

                }); //跳转到首页
                // wx.redirectTo({
                //   url: '/pages/index/index'
                // })
              }
            }
          });
          return;
        } else {
          uni.hideLoading(); //过滤设备-z

          let scanList_new = new Array();
          let device_list = app.globalData.device_list;

          for (let i = 0; i < scanList.length; i++) {
            for (let x = 0; x < device_list.length; x++) {
              if (scanList[i].name == device_list[x].dev_sn) {
                scanList[i]['name'] = device_list[x].dev_name; //用户私钥

                scanList[i]['wxapp_ekey'] = device_list[x].wxapp_ekey;
                scanList_new.push(scanList[i]);
              }
            }
          }

          if (scanList_new.length == 0) {
            uni.hideLoading();
            uni.showModal({
              content: '未获取到授权设备',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  uni.navigateBack({
                    delta: 1 // 返回上一级页面。

                  }); //跳转到首页
                  // wx.redirectTo({
                  //   url: '/pages/index/index'
                  // })
                }
              }
            });
            return;
          }

          that.setData({
            scanList: scanList_new
          });
        }
      });
    },
    // 执行开门操作
    openDoor: function (event) {
      uni.showLoading({
        title: '开门中...',
        mask: true
      });
      var deviceId = event.currentTarget.dataset.deviceid;
      var wxapp_ekey = event.currentTarget.dataset.wxapp_ekey;
      console.info(deviceId + "=" + wxapp_ekey);
      tmsdk.openDoor(deviceId, wxapp_ekey, function (res) {
        uni.hideLoading();
        console.log("----res.errCode:", res.errCode); // 暂时忽略10008错误码，这是其余所有系统上报的异常

        if (res.errCode === 0 || res.errCode === 10008) {
          uni.showToast({
            title: '开门成功',
            icon: "success"
          });
        } else {
          uni.showToast({
            title: '开门失败,' + '错误码：' + res.errCode
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
.container {
  align-items: center;
}

.list-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border-radius: 10rpx;
  padding: 30rpx;
  box-sizing: border-box;
  background: #fff;
  margin: 30rpx;
  position: relative;
  line-height:40rpx;
}

.list-item:last-child {
  border-style: none;
}

.button {
  position: fixed;
  width: 690rpx;
  bottom: 30rpx;
}

.openBtn {
  float: right;
}

.openBtn {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translate(0, -50%);
  border: 1px solid $base-btn-color;
  height: 40rpx;
  line-height: 40rpx;
  padding: 0 20rpx;
  border-radius: 6rpx;
  color: #fff;
  background: $base-btn-color;
}
.default {
  text-align: center;
  position: fixed;
  left: 50%;
  top: 40%;
  transform: translate(-50%, -50%);
}
.default text{
	color: #AAAAAA;
}
.default image {
  height: 160rpx;
  display: inline-block;
}
.empty-wrap{
	background-color: #FFFFFF;
	min-height: 100vh;
}

</style>