<template>
  <view class="container">
    <view class="text" @click="openBluetoothAdapter" v-if="issearch">没有搜到想要的？点击重新搜索</view>
    <view class="point-area">
      <view class="point point-10"></view>
      <view class="point point-40"></view>
      <view class="point point-80"></view>
      <view class="point point-100"></view>
      <view class="point point-120"></view>
    </view>
    <view class="list">
      <view class="item" v-for="(item,index) in devList" :key="index" @click="handleWeight(item)">
        <image :src="item.img"></image>
        <text>{{item.faccode}}</text>
      </view>
    </view>
    <view class="tips" v-if="isdevTip">
      <view>提示：</view>
      <text>1.请确保设备是已激活</text>
      <text>2.请确保设备是开机状态</text>
      <text>3.请确定手机蓝牙、位置信息已打开</text>
      <text>4.ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
    </view>
  </view>
</template>

<script>
  let that;
  let myTime;
  import {
    mapState
  } from "vuex";
  export default {
    data() {
      return {
        Unload: false,
        issearch: false,
        isdevTip: false,
        devList: [],
        devicesList: [],
      }
    },
    computed: {
      ...mapState(["user", "isConnected", "isBluetoothTyle", "appTheme"]),
    },
    onLoad() {
      that = this
      // 导航栏颜色
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: that.appTheme,
      })
      that.openBluetoothAdapter()
      that.onBLEConnectionStateChange()
      uni.onBluetoothAdapterStateChange(function(res) {
        that.$store.commit("changeBluetooth", res.available);
      })
    },
    onUnload: function() {
      let that = this
      if (!that.Unload) {
        that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
        that.closeBLEConnection()
        that.closeBluetoothAdapter()
        console.log("搜索页返回")
      }
    },
    watch: {
      isBluetoothTyle: function() {
        let that = this
        if (!that.isBluetoothTyle) {
          that.issearch = true
          that.isdevTip = true
          that.devList = []
          clearTimeout(myTime);
          that.closeBLEConnection()
          that.closeBluetoothAdapter()
          that.stopBluetoothDevicesDiscovery()
        }
      }
    },
    methods: {
      // 初始化蓝牙
      openBluetoothAdapter() {
        let that = this
        uni.openBluetoothAdapter({
          success: e => {
            console.log("蓝牙初始化成功")
            that.issearch = false
            that.isdevTip = false
            that.devList = []
            that.startBluetoothDeviceDiscovery()
          },
          fail: e => {
            that.$tools.msg("请打开蓝牙！安卓系统需打开蓝牙、定位权限；ios系统需打开设置——>应用——>微信里的蓝牙权限！")
          }
        });
      },
      // 监听蓝牙连接状态
      onBLEConnectionStateChange() {
        let that = this
        uni.onBLEConnectionStateChange(function(res) {
          console.log("蓝牙连接状态", res.connected)
          that.$store.commit("changeConnected", res.connected);
        })
      },
      /**
       * 停止搜索蓝牙设备
       */
      stopBluetoothDevicesDiscovery() {
        uni.stopBluetoothDevicesDiscovery({
          success: e => {
            console.log("停止搜索蓝牙设备", e)
          },
        });
      },
      // 开始搜寻附近的蓝牙外围设备
      startBluetoothDeviceDiscovery() {
        let that = this
        uni.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false, //是否允许重复上报同一设备
          // interval: 200,
          success: res => {
            that.onBluetoothDeviceFound();
          },
          fail: res => {
            that.$tools.msg("请打开蓝牙！安卓系统需打开蓝牙、定位权限；ios系统需打开设置——>应用——>微信里的蓝牙权限！")
          }
        });
      },
      /**
       * 发现外围设备
       */
      onBluetoothDeviceFound() {
        var that = this;
        uni.onBluetoothDeviceFound(res => {
          res.devices.forEach(device => {
            if (!device.name && !device.localName) {
              return
            }
            console.log("设备列表", device, device.name.indexOf("ELK"))
            let buff = ""
            if (device.name.indexOf("ELK") != -1 && device.advertisServiceUUIDs.length && device.advertisServiceUUIDs[0].indexOf("F0A0") != -1) {
              buff = device.advertisData.slice(0, 8)
            } else {
              buff = device.advertisData.slice(-6)
            }
            device.mac = new Uint8Array(buff)
            let tempMac = Array.from(device.mac)
            if (device.name.indexOf('My') == -1) {
              tempMac.reverse()
            }
            device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
            const foundDevices = that.devicesList
            const idx = that.$tools.inArray(foundDevices, "deviceId", device.deviceId)
            if (idx === -1) {
              that.devicesList.push(device);
              if (device.macAddr != "") {
                that.handleDevType(device.macAddr)
              }
            }
            // console.log("设备列表", that.devicesList)
          })
        });
        that.handleMyTime()
      },
      handleMyTime() {
        var that = this;
        myTime = setTimeout(function() {
          if (!that.devList.length) {
            that.isdevTip = true
            that.devList = []
          }
          that.issearch = true
          clearTimeout(myTime);
          that.closeBLEConnection()
          that.closeBluetoothAdapter()
          that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
        }, 30000);
      },
      // 排查设备
      handleDevType(sn) {
        that = this
        that.$model.getdevdetail({
          sn: sn,
          height: 0,
          weight: 0,
          imp: 0
        }).then(res => {
          if (res.code == 0) {
            res.data.deviceId = sn
            that.devList.push(res.data);
          }
        })
      },
      handleWeight(item) {
        let that = this
        that.Unload = true
        clearTimeout(myTime);
        console.log("跳转测量", item)
        if (item.bletype != 2) {
          that.stopBluetoothDevicesDiscovery()
        }
        uni.redirectTo({
          url: item.bleurl
        })
      },
      /**
       * 断开蓝牙模块
       */
      closeBluetoothAdapter() {
        let that = this;
        uni.closeBluetoothAdapter({
          success: res => {
            console.log('蓝牙模块关闭成功');
          }
        })
      },
      /**
       * 断开蓝牙连接
       */
      closeBLEConnection() {
        var that = this;
        uni.closeBLEConnection({
          success: res => {
            console.log('断开蓝牙连接成功');
          }
        });
      },
    }
  }
</script>

<style scoped lang="scss">
  .text {
    position: absolute;
    top: 0px;
    width: 100%;
    text-align: center;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    color: $greencolor;
    font-weight: bold;
  }

  .tips {
    position: absolute;
    width: 100%;
    bottom: 15px;
    line-height: 24px;

    view {
      font-size: 14px;
      color: $greencolor;
      font-weight: bold;
      margin-left: 15px;
    }

    text {
      font-size: 12px;
      width: 100%;
      display: block;
      margin-left: 20px;
      color: #999;
    }
  }

  .list {
    position: absolute;
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .item {
      width: 30%;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      position: absolute;
      left: 55%;
      top: -10px;

      image {
        width: 45px;
        height: 45px;
        border-radius: 50%;
      }

      text {
        display: block;
        width: 100%;
        font-size: 12px;
        color: #666;
        margin-top: 5px;
        text-align: center;
      }
    }

    .item:nth-of-type(2) {
      left: calc(55% - 60px);
      top: 50px;
    }

    .item:nth-of-type(3) {
      left: calc(50% - 140px);
      top: 90px;
    }

    .item:nth-of-type(4) {
      left: calc(61% + 20px);
      top: 70px;
    }

    .item:nth-of-type(5) {
      left: 20%;
      top: -100px;
    }

    .item:nth-of-type(6) {
      left: calc(20% - 16px);
      top: -38px;
    }

    .item:nth-of-type(7) {
      left: 0;
      top: 15px;
    }

    .item:nth-of-type(8) {
      left: calc(20% + 75px);
      top: -150px;
    }

    .item:nth-of-type(9) {
      left: calc(20% + 96px);
      top: -80px;
    }

    .item:nth-of-type(10) {
      left: 37px;
      top: -170px;
    }

    .item:nth-of-type(11) {
      left: calc(20% + 75px);
      top: 130px;
    }

    .item:nth-of-type(12) {
      left: -10px;
      top: -104px;
    }

    .item:nth-of-type(13) {
      left: calc(47% + 75px);
      top: -150px;
    }

    .item:nth-of-type(14) {
      left: calc(53% + 75px);
      top: -50px;
    }

  }

  .container {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
  }

  // 中心园
  .container::after {
    content: "";
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #fbb780;
    position: absolute;
    z-index: 9;

  }

  /* 定义范围*/
  .point-area {
    text-align: center;
    position: relative;
    width: 400rpx;
    height: 400rpx;
    transition: opacity 0.5s ease-out;
  }

  .point-10,
  .point-40,
  .point-80,
  .point-100,
  .point-120 {
    width: 100%;
    height: 100%;
  }

  .point-10:after,
  .point-40:after,
  .point-80:after,
  .point-100:after,
  .point-120:after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border-radius: 50%;
    opacity: 0;
    border: 1px solid #f7cb6b;
    animation-play-state: paused;
    -webkit-animation-play-state: paused;
  }

  .point-10:after {
    content: '';
    animation: ripple 3000ms linear 0ms infinite;
  }

  .point-40:after {
    content: '';
    animation: ripple 3000ms linear 600ms infinite;

  }

  .point-80:after {
    content: '';
    animation: ripple 3000ms linear 1200ms infinite;
  }

  .point-100:after {
    content: '';
    animation: ripple 3000ms linear 1800ms infinite;
  }

  .point-120:after {
    content: '';
    animation: ripple 3000ms linear 2400ms infinite;
  }


  @keyframes ripple {

    0% {
      opacity: 0;
      transform: scale(0.1);
    }

    50% {
      opacity: 0.8;
      transform: scale(1);
    }

    100% {
      opacity: 0.2;
      transform: scale(2.2);
    }

  }
</style>
