<template>
  <view class="device">
    <view class="rssi">
      <view class="signal">
        <view
          class="cell"
          v-for="h in [4, 6, 8, 10]"
          :key="h"
          :style="{
                  height: h + 'px',
                  background:
                    h &lt;= getRSSIStyle(Bluetooth.device.RSSI).h
                      ? getRSSIStyle(Bluetooth.device.RSSI).BC
                      : '#BBBBBB',
                }"
        />
      </view>
    </view>
    {{ Bluetooth.device.name || Bluetooth.device.deviceId }}
  </view>
</template>

<script>
import { hexMD5 } from "../../pages/login/modules/md5";

export default {
  props: {
    onFeedback: {
      type: Function,
    },
  },
  data() {
    return {
      Bluetooth: {},
      circulation: null,
    };
  },
  beforeDestroy() {
    clearInterval(this.circulation);
  },
  methods: {
    init() {
      let that = this;
      this.Bluetooth = this.$Http.Bluetooth;
      console.log("连接蓝牙设备详情", this.$Http.Bluetooth);
      uni.onBLEConnectionStateChange(function (res) {
        if (!res.connected && that.circulation) {
          uni.showModal({
            content: "蓝牙设备已断开连接",
            showCancel: false,
          });
          that.$Http.setDetailMode(0);
          clearInterval(that.circulation);
          that.circulation = null;
        }
      });
      this.circulation = setInterval(() => {
        uni.getBLEDeviceRSSI({
          deviceId: that.Bluetooth.device.deviceId,
          success: (success) => {
            console.log("监听信号强度", success);
            if (success.errCode == 0) that.Bluetooth.device.RSSI = success.RSSI;
          },
        });
      }, 3000);

      this.startNotice();
    },
    closeBLEConnection() {
      let that = this;
      uni.closeBLEConnection({
        deviceId: that.Bluetooth.device.deviceId,
        success(res) {
          that.$Http.setDetailMode(0);
          clearInterval(that.circulation);
          that.circulation = null;
        },
      });
      uni.closeBluetoothAdapter();
    },
    /* 发送 */
    send(content = {}, item) {
      content.ts = Date.now();
      content.msgid = hexMD5(
        JSON.stringify({ w_functionid: item.w_functionid, ...msg })
      );

      item.msgid = content.msgid;
      item.msg = content;
      console.log("发送通信内容", item.msg);

      let msg = JSON.stringify({
        d: content.d,
        password: content.password,
        msgid: content.msgid,
        ts: content.ts,
      });

      let that = this;
      const buffer = new ArrayBuffer(msg.length);
      const dataView = new DataView(buffer);
      for (var i = 0; i < msg.length; i++) {
        dataView.setUint8(i, msg.charAt(i).charCodeAt());
      }
      uni.writeBLECharacteristicValue({
        deviceId: that.Bluetooth.device.deviceId,
        serviceId: that.Bluetooth.services.uuid,
        characteristicId: that.Bluetooth.Wcharacteristic.uuid,
        value: buffer,
        success(res) {
          console.log("发送信息", res);
        },
        fail(err) {
          console.error("发送信息失败", err);
          that.handleFail(err);
        },
      });
    },
    /* 模拟接收 */
    fanhui(value) {
      let resHex = this.ab2hex(value);
      let result = JSON.parse(this.hexCharCodeToStr(resHex));
      delete result.d;
      result.status = 1;
      this.$emit("onFeedback", result);
    },
    /* 开始监听 */
    startNotice() {
      let that = this;
      uni.notifyBLECharacteristicValueChange({
        deviceId: that.Bluetooth.device.deviceId,
        serviceId: that.Bluetooth.services.uuid,
        characteristicId: that.Bluetooth.Ncharacteristic.uuid,
        state: true,
        success(res) {
          console.log("监听信息", res);
          uni.onBLECharacteristicValueChange((res) => {
            let resHex = that.ab2hex(res.value);
            let result = that.hexCharCodeToStr(resHex);
            console.log("Notice", result);
            that.$emit("onFeedback", JSON.parse(result));
          });
        },
        fail(err) {
          console.error("监听信息失败", err);
          that.handleFail(err);
        },
      });
    },
    handleFail(fail) {
      const codes = {
        0: "ok",
        "-1": "已连接 ",
        10000: "未初始化蓝牙适配器",
        10001: "当前蓝牙适配器不可用",
        10002: "没有找到指定设备",
        10003: "连接失败",
        10004: "没有找到指定服务",
        10005: "没有找到指定特征值",
        10006: "当前连接已断开",
        10007: "当前特征值不支持此操作",
        10008: "其余所有系统上报的异常",
        10009: "系统版本低于 4.3 不支持 BLE",
        10010: "已连接",
        10011: "配对设备需要配对码",
        10012: "连接超时",
        10013: "连接 deviceId 为空或者是格式不正确",
      };
      uni.showModal({
        content: codes[fail.errCode] || fail.errMsg,
        showCancel: false,
        confirmText: "确认",
      });
      this.$emit("onFeedback", {
        status: 999,
        msgid: 23232323,
      });
    },
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },
    hexCharCodeToStr(hexCharCodeStr) {
      var trimedStr = hexCharCodeStr.trim();
      var rawStr =
        trimedStr.substr(0, 2).toLowerCase() === "0x"
          ? trimedStr.substr(2)
          : trimedStr;
      var len = rawStr.length;
      if (len % 2 !== 0) {
        alert("存在非法字符!");
        return "";
      }
      var curCharCode;
      var resultStr = [];
      for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16);
        resultStr.push(String.fromCharCode(curCharCode));
      }
      return resultStr.join("");
    },
    getRSSIText: function (rssi) {
      let text = "";
      if (rssi >= -70) {
        text = "可连接";
      } else if (rssi < -90) {
        text = "不可连接";
      } else {
        text = "信号差";
      }
      return text + `(${rssi})`;
    },
    getRSSIStyle: function (rssi) {
      let obj = {
        h: 10,
        BC: "#5AB73F",
      };
      if (rssi < -60 && rssi >= -69) {
        obj.h = 8;
      } else if (rssi <= -70 && rssi >= -79) {
        obj.h = 6;
        obj.BC = "#F29C37";
      } else if (rssi <= -80 && rssi >= -89) {
        obj.h = 4;
        obj.BC = "#EB4B5C";
      } else if (rssi <= -90) {
        obj.h = 0;
      }
      return obj;
    },
  },
};
</script>

<style lang="scss" scope>
.device {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 14px;
  color: #fff;
  font-weight: 700;
  padding-left: 5px;
  padding-bottom: 5px;

  .rssi {
    display: flex;
    align-items: center;
    height: 17px;
    margin: 0 6px;
    .text {
      font-family: PingFang SC, PingFang SC;
      font-size: 12px;
      color: #666666;
      margin-right: 18px;
    }

    .signal {
      display: flex;
      align-items: flex-end;
      height: 12px;

      .cell {
        width: 3px;
        border-radius: 1px;
        margin-right: 1px;
      }
    }
  }
}
</style>