import game_store from "../store/game";
import ble_store from "../store/bluetooth";
import Notify from "../../static/vant/notify/notify";
import {LogInDb} from "@/requests/log";
import {addRawData} from "../requests/game";


var $ff = "ff";
var $8f = "ffffffff"
var control_close = false
var current_device_sn = ""
//记录当前脑机的mac地址
var current_device_mac = "";
//记录教具连接状态
var connect_toy = true;
//记录教具连接的id
var current_toy_id = "00";
//记录教具的UUID
var current_toy_UUID = "";

//标记是否打开脑控
var FlagOpenControl = false;

var ToyPower = 0;

//Math.round(new Date() / 1000)
var logTime = "";

var current_hex = "";

var is_new = game_store.getters.getIsNew();

//2021年11月10日14:59:38
// 0为旧 1为新
var services = [
  "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
  "0000fff0-0000-1000-8000-00805f9b34fb".toUpperCase()
]
var charateristics = [
  {
    notify: "6e400003-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
    write: "6e400002-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase()
  },
  {
    notify: "0000fff1-0000-1000-8000-00805f9b34fb".toUpperCase(),
    write: "0000fff2-0000-1000-8000-00805f9b34fb".toUpperCase()
  },
]

function getServicesAndCharateristc() {
  //获取当前设备名称
  // let $brainSn = game_store.getters.getDeviceSn();
  let $deviceId = game_store.getters.getDeviceId();
  let $serviceId = game_store.getters.getServiceId();
  let $index = services.indexOf($serviceId.toUpperCase())
  // let $index = $brainSn.toUpperCase().indexOf("JELLYFISH") != -1 ? 0 : 1;
  return {
    deviceId: $deviceId,
    service: "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
    charateristic: charateristics[0]
  }
}

var update_state = true;
//全局升级下标
var update_index = 0;
//序列下标1
var update_seq1_index = 0;
//序列下标2
var update_seq2_index = 0;
var totalBuffer = [];
// 脑机model
var model = "";
//脑机固件版本
var version = "";


var origin_buffer = "";

var raw_data_open = false;
var raw_status = false
var control_close_intv = undefined
export default {
  //变量

  /**
   *  todo:打开大包数据
   */
  sendOpenBigData() {
    this.SendOrder('ff')
  },
  /**
   *  todo:关闭大包数据
   */
  sendCloseBigData() {
    this.SendOrder('00')
  },
  /**
   *  todo:获取当前连接的教具类型
   */
  sendGetToyType() {
    this.SendOrder('06')
  },
  /**
   *  todo:开启脑控
   */
  sendControl() {
    let that = this;
    // 先发第一次
    that.SendOrder('07')
    wx.showLoading({
      title: "正在启动"
    })
    // let $intv = setInterval(() => {
    //   if (FlagOpenControl) {
    //     //设置打开脑控为false
    //     FlagOpenControl = false;
    //     clearInterval($intv)
    //     wx.hideLoading()
    //   } else {
    //     that.SendOrder('07')
    //   }
    // }, 3000)
  },
  /**
   *  todo:关闭脑控
   */
  sendControlClose() {
    let that = this
    control_close = false;
    control_close_intv = setInterval(() => {
      if (!control_close) {
        that.SendOrder('09')
        //如果是jellyfish则发送00教具
        if (!is_new) {
          that.sendConnectOneToMore('00')
        }

      } else {
        //设置打开脑控为false
        FlagOpenControl = false;
        clearInterval(control_close_intv)
        //清空当前数据
        that.clearLocalDatas()
      }
    }, 1000)
  },
  /**
   *  todo:发送一对多连接
   */
  sendConnectOneToMore(id) {
    this.WriteBufferInBle(`03 00 ${id} 00 0A`);
  },
  /**
   *  todo:发送一对一连接
   */
  sendConnectOneToOne(id) {
    current_toy_id = id;
    this.WriteBufferInBle(`03 00 ${id} 01 0A`)
  },

  /**
   *  todo:获取教具电量
   */
  sendToyPower() {
    let that = this;
    if (is_new) {
      let $connect_false_count = 0;
      let toy_intv = setInterval(() => {
        let $game_status = game_store.getters.getGameStatus();
        if (connect_toy) {
          that.SendOrder('8a')
        } else {
          if ($game_status != 1) {
            clearInterval(toy_intv)
          }
        }
      }, 3000)
    } else {
      console.log("旧脑机不支持获取教具电量")
    }
  },

  /**
   *  todo:获取大包数据进行绘制图表
   */
  get_big_data(hex) {
    let hexAry = []
    for (let i = 0; i < hex.length; i += 2) {
      hexAry.push(hex.substr(i, 2))
    }
    if (hex.substr(0, 6) != "555520") {
      return false;
    }
    //当s1为 00时 数据有效
    // let hex_str = hex.substr(hex.indexOf("555520"))
    // let $s1 = hex_str.substr(8, 2);
    let $s1 = hexAry[4]
    if ($s1 !== "00") {
      return false;
    }

    //专注度数据
    let $att = parseInt(hexAry[6], 16)
    //放松度数据
    let $med = parseInt(hexAry[8], 16)

    let idx = 0
    let dataIndex = ['delta', 'theta', "low_alpha", "high_alpha", "low_beta", "high_beta", "low_gamma", "middle_gamma"]
    let datas = []
    hexAry.pop()
    for (let i = 11; i < hexAry.length; i += 3) {
      let num_1 = parseInt(hexAry[i], 16)
      let num_2 = parseInt(hexAry[i + 1], 16)
      let num_3 = parseInt(hexAry[i + 2], 16)
      let show_value = num_1 + num_2 + num_3;
      let basic_value = parseInt("0x" + hexAry[i] << 16 | "0x" + hexAry[i + 1] << 8 | "0x" + hexAry[i + 2], 16)
      datas[dataIndex[idx]] = show_value
      datas[`${dataIndex[idx]}_basic`] = basic_value
      idx += 1;
    }
    datas['att'] = $att;
    datas['med'] = $med;
    return datas
  },
  /**
   *  todo:获取设备电量
   */
  get_device_elc(hex) {
    if (hex.substr(0, 8) != "55550203") {
      return false;
    }
    let $power = parseInt("0x" + hex.substr(8, 2));
    return $power;
  },

  /**
   *  todo:监听蓝牙连接状态
   */
  watch_bluetooth_status($this) {
    let that = this;
    // 微信自身监听低功耗蓝牙连接状态的改变事件
    wx.onBLEConnectionStateChange((res) => {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      ble_store.setters.setBluetoothLinkStatus(res.connected);
      LogInDb(`${that.getNowTime()} 监听脑机断连`)
      if (res.connected == false) {
        //判断游戏是否游戏中
        let $game_status = game_store.getters.getGameStatus();
        if ($game_status == 1) {
          // $that.game_finished();
          Notify({
            type: 'danger',
            duration: 0,
            message: '智脑机已断开连接，正在尝试重新连接',
            onOpened() {
              that.reconnect(res.deviceId, $this)
            }
          });
          control_close = true
          // connect_toy = false;
        } else {
          //关闭脑控
          connect_toy = false;
          game_store.setters.setGameStatus(0);
          // 清空链接得设备 三值
          game_store.setters.clearDeviceToy();
          $this.connect_toy = 0;
          $this.connect_show = false;
          $this.device_bg = false;
          $this.change_toy_connect_status(0);
          $this.device_status = 0;
          $this.device = {}
          $this.toy_UUID = "";
          $this.$forceUpdate();
          wx.closeBluetoothAdapter();
          version = "";
        }
      }
    });
  },

  /**
   * todo:重新连接蓝牙
   */
  reconnect($deviceId, $this) {
    let that = this;
    let $deviceInfo = getServicesAndCharateristc();
    //重连的次数
    let $connect_count = 0;
    let $rec = setInterval(() => {
      let $game_status = game_store.getters.getGameStatus();
      if ($game_status == 1) {
        wx.createBLEConnection({
          deviceId: $deviceInfo.deviceId,
          success(res) {
            clearInterval($rec)
            Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
            LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
            let $system = wx.getSystemInfoSync()
            if ($system.platform == 'ios') {
              that.getBLEDeviceServices($deviceInfo.deviceId)
              that.watchingDevice($this)
            } else {
              that.openNotify($this)
              that.watch_bluetooth_status($this);
            }
            // that.sendToyPower();

          },
          fail(res) {
            Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
            game_store.setters.setGameCloseStatus(1);
          }
        })
        if ($connect_count >= 3) {
          $this.game_finished();
          clearInterval($rec)
        }
        $connect_count += 1;
      } else {
        clearInterval($rec)
      }
    }, 7000)

  },

  /**
   * todo 获取蓝牙设备服务
   * @param deviceId
   */
  getBLEDeviceServices(deviceId) {
    const that = this;
    current_device_mac = deviceId
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          console.log("serviceItem:" + res.services[i].uuid);
          if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
            console.log("SelectedServiceItem:" + res.services[i].uuid);
            that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
            game_store.setters.setServiceId(res.services[i].uuid)
            is_new = game_store.getters.getIsNew()
            return;
          }
        }
      },
      fail(res) {
        let deviceId = wx.getStorageSync('deviceId');
        //断开蓝牙连接
        wx.closeBLEConnection({
          deviceId: deviceId
        });
      },
    });
  },

  /**
   * todo 获取蓝牙设备某个服务中所有特征值
   */
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    console.log(deviceId, serviceId);
    const $this = this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log("getBLEDeviceCharacteristics success", res.characteristics);
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i];
          let writeState = null;
          if (serviceId.indexOf("0001") != -1) {
            writeState = item.properties.write && item.uuid.indexOf("0002") != -1;
          } else {
            writeState = item.properties.write;
          }
          if (writeState) {
            // if (item.properties.write) {
            $this.deviceId = deviceId;
            $this.serviceId = serviceId;
            $this.cid = item.uuid;
            //打开数据帧
            $this.sendOpenBigData();
          }

          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            });
          }
        }
      },
      fail(res) {
        let deviceId = wx.getStorageSync('deviceId');
        //断开蓝牙连接
        wx.closeBLEConnection({
          deviceId: deviceId
        });
      },
    });
  },

  openNotify($this) {
    let that = this;
    let $deviceInfo = getServicesAndCharateristc();
    console.log($deviceInfo)
    wx.notifyBLECharacteristicValueChange({
      deviceId: $deviceInfo.deviceId,
      serviceId: $deviceInfo.service,
      characteristicId: $deviceInfo.charateristic.notify,
      state: true,
      success() {
        that.watchingDevice($this)
      }
    });
  },

  /**
   * todo ArrayBuffer转16进度字符串示例
   * @param buffer
   * @returns {string}
   */
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ("00" + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join("");
  },


  /**
   * todo 监听脑机数据
   * @param $this
   */
  watchingDevice($this) {
    const that = this;
    let DeviceId = game_store.getters.getDeviceId();
    wx.onBLECharacteristicValueChange((characteristic) => {

      // 获取脑机信号值
      wx.getBLEDeviceRSSI({
        deviceId: DeviceId,
        success(res) {
          if (game_store.getters.getGameStatus() == 1) {
            $this.rssi = res.RSSI;
          }
        }
      })

      let hexStr = that.ab2hex(characteristic.value);
      // console.log("数据", hexStr, "长度", hexStr.length / 2);

      if (hexStr.toUpperCase().indexOf("AADD") != -1 || hexStr.toUpperCase().indexOf("AAEE") != -1 && update_state == false) {
        let nowTime = Math.round(new Date() / 1000);
        console.log("应答", hexStr, '时间：' + that.getNowTime(), "长度", hexStr.length / 2);
        LogInDb(`${that.getNowTime()} 应答：${hexStr}`)
      }
      let $data = that.get_big_data(hexStr);
      let $game_status = game_store.getters.getGameStatus();

      // 教具断链
      if (hexStr.toUpperCase().indexOf("AAEE70") != -1) {
        connect_toy = false
        wx.showModal({
          content: "教具已断开",
          success(res) {
            if (res.confirm) {
              //重连机制
              if ($game_status == 1) {
                $this.game_finished();
              }
            }
          }
        })

      }


      if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") != -1) {
        that.SendOrder("8a")
      }

      //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
      // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") != -1){
      //   that.connect_toy = false;
      // }

      if (hexStr.toUpperCase().indexOf("AAEE07") != -1) {
        that.sendControl();
      }
      // 2021年10月20日17:18:13 判断教具 连接
      if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
        //没连接上教具
        if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
          if (is_new) {
            $this.change_toy_connect_status(3);
          }
          return false;
        }
        let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
        let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
        let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
        console.log("连接", $hex_index)
        console.log("教具", $toy_id)
        // 连接上教具
        if (new RegExp("00").test($hex_index) == true) {
          if (is_new) {
            that.sendConnectOneToOne($toy_id)
            $this.current_hex = `03 00 ${$toy_id} 01 0A`
            console.log("一对多")
          } else {
            $this.current_hex = "";
            wx.showToast({
              title: "已连接到" + $this.toy_item.name
            });
            $this.toy_connected = true;
            $this.change_toy_connect_status(2);
          }
        }
        if (new RegExp("01").test($hex_index) == true) {
          console.log("一对一")
          $this.current_hex = "";
          wx.showToast({
            title: "已连接到" + $this.toy_item.name
          });
          $this.toy_connected = true;
          connect_toy = true;

          $this.change_toy_connect_status(2);

          //连接成功后 获取一次教具名称
          //TODO 2022-5-25 08:51:15 延迟发送教具UUID
          //2022年5月25日17:21:57 从2秒更换到3秒
          // 判断冥想模式不发送获取教具名字
          if ($toy_id != 80) {
            setTimeout(() => {
              that.SendOrder('87')
            }, 3000)

            // 更改为不断获取教具电量
            setTimeout(() => {
              that.sendToyPower();
            }, 5000)
          }

        }

      }

      //2021年11月23日10:39:49
      // 获取教具名称
      if (hexStr.toUpperCase().indexOf("AADD87") != -1) {
        let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
        let $datas = that.DoAnalysis($mHexStr, 10)
        let $number = $datas.match(/\d+/)
        let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM"}
        let $sn = toy_list_pre[current_toy_id] + $number;
        $this.toy_sn = $sn;
        //获取教具电量
        // that.SendOrder('8a')
      }
      if (hexStr.toUpperCase().indexOf("AAEE87") != -1) {
        //获取教具电量
        if (current_toy_id != '80') {
          that.SendOrder('87')
        }
      }

      //2021年10月21日16:30:07
      // 获取教具电量
      if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
        let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
        let $power = parseInt($_hexStr.substr(0, 2), 16)
        let $voltage = parseInt($_hexStr.substr(2, 2), 16)
        connect_toy = true;
        // $this.toy_power = Math.round(that.CalBLEPower($voltage));
        if ($power > 0) {
          $this.toy_power = $power
          $this.toy_voltage = $voltage
          ToyPower = $power;
        }


        if (current_toy_UUID == "") {
          //获取教具UUID
          that.SendOrder('84')
        }
      }

      //监听佩戴正确
      if (hexStr.substr(0, 6) == "555520") {
        //当s1为 00时 数据有效
        let $s1 = hexStr.substr(8, 2);
        // console.log("监听脑机是否带正：", $s1 == '00')

        $this.device_bg = $s1 == "00";
      }

      // 2021年10月25日09:15:50
      // 读取教具UUID
      if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
        let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
        let $datas = hexStr.substr($hex_index, 10);
        if ($datas != "0000000000") {
          console.log("以获取UUID：" + $datas)
          current_toy_UUID = $datas;
          $this.toy_UUID = $datas;
        }
      }


      if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
        control_close = true;
        connect_toy = false;
      }

      //收到发送UUID的应答立马发送连接教具的指令
      if (hexStr.toUpperCase().indexOf("AADD8E") != -1) {
        //发送教具连接
        that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
      }


      // 处理打开脑控的应答
      if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
        ble_store.setters.setBluetoothLinkStatus(true)
        FlagOpenControl = true;
      }

      //todo 监听脑机电量
      if (hexStr.substr(0, 8) == "55550203") {
        let $power = parseInt(hexStr.substr(8, 2), 16);
        let $voltage = parseInt(hexStr.substr(10, 2), 16);
        //监听是否插入USB
        $this.hasUsb = $voltage.toString().substr(0, 1) == 1
        //  监听脑机电量
        if ($power) {
          // console.log("当前脑机电量:", $power)
          $this.device_power = $power;
          $this.device_voltage = $voltage;
        }
        if ($power < 10 && $power > 0) {
          wx.showToast({
            title: "脑机电量不足",
            icon: "none",
            duration: 2000,
            success() {
              // $this.change_device_status(0);
            },
          });
        }
      }

      //游戏中模块
      if ($game_status == 1 && $data) {
        $this.do_datas($data);
      }


      // 监听原始数据
      if (hexStr.substr(0, 6) == "5555e2") {
        let _buffer = that.doOriginBufferToData(hexStr)
        if ($game_status == 1) {
          wx.setStorageSync('origin_buffer', wx.getStorageSync('origin_buffer') + _buffer.join(',') + ",")
        }
      }

      //todo 打开原始数据
      if (hexStr.toUpperCase().indexOf("AADD04") != -1) {
        raw_data_open = true;
        that.Send2BOrder(true)
        wx.setStorageSync('origin_buffer', "");
      }

      //todo 接收脑机关机指令
      if (hexStr.toUpperCase().indexOf("AADD5A00000000A5") != -1) {
        Notify({
          type: 'danger',
          duration: 0,
          message: '智脑机已关机,训练结束',
          onOpened() {
            setTimeout(() => {
              $this.game_finished();
              clearInterval(control_close_intv)
            }, 2000)
          }
        });

      }
    });
  },

  /**
   * todo 游玩时间倒计时
   * @param value
   * @returns {string}
   */
  formatPlaySeconds(value) {
    // 字符串转数字
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    if (secondTime > 60) {
      //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
      //如果分钟大于60，将分钟转换成小时
    }
    var result = "" + parseInt(secondTime);

    if (minuteTime > 0) {
      if (result.length == 1) {
        result = "0" + result;
      }
      if (parseInt(minuteTime).toString().length == 1) {
        minuteTime = "0" + parseInt(minuteTime);
      }
      result = "" + minuteTime + ":" + result;
    } else {
      result = "00:" + result;
    }
    return result;
  },

  /**
   * todo 根据错误代码返回字符串信息
   * @param errCode
   * @returns {string}
   * @constructor
   */
  GetopenBluetoothAdapterError(errCode) {

    let $errmsg = "";
    if (errCode == 10000) {
      $errmsg = "未初始化蓝牙适配器"
    }

    if (errCode == 10001) {
      $errmsg = "当前蓝牙适配器不可用"
    }

    if (errCode == 10002) {
      $errmsg = "没有找到指定设备"
    }

    if (errCode == 10003) {
      $errmsg = "连接失败"
    }

    if (errCode == 10006) {
      $errmsg = "当前连接已断开"
    }

    return $errmsg;
  },

  /**
   * todo 写入buffer
   * @param $hex
   * @param $buffer_len
   * @constructor
   */
  WriteBufferInBle($hex, $buffer_len = 8) {
    let that = this;
    let $deviceInfo = getServicesAndCharateristc();
    let $hex_header = "aa cc ";
    // let $hex = "03 00 01 00 0a";

    let $hex_sum = 0;
    let $hex_ary = $hex.split(" ");
    $hex_ary.forEach(($val, $index) => {
      $hex_sum += parseInt($val, 16);
    })

    let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);

    $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
    let buffer = new ArrayBuffer($buffer_len);
    let dataView = new DataView(buffer);
    $hex_ary = $hex.split(" ");
    $hex_ary.forEach(($val, $index) => {
      dataView.setUint8($index, parseInt($val, 16))
    })


    if (!$deviceInfo.charateristic.write) {
      return false;
    }
    wx.writeBLECharacteristicValue({
      deviceId: $deviceInfo.deviceId,
      serviceId: $deviceInfo.service,
      characteristicId: $deviceInfo.charateristic.write,
      value: buffer,
      success: function (res) {
        if ($buffer_len <= 16) {
          console.log($hex + ',写入成功,时间：' + that.getNowTime())
        } else {
          console.log('写入成功,时间：' + that.getNowTime())
        }
        // LogInDb(`${that.getNowTime()} ${$hex}',写入成功`)
      },
      fail: function (err) {
        console.log($hex + "写入失败", err);
      },
    });
  },

  /**
   * todo写入8位指令
   * @param id 末尾id
   * @constructor
   */
  SendOrder(id) {
    let $hexStr = `03 00 00 00 ${id}`;
    this.WriteBufferInBle($hexStr)
  },

  /**
   * todo 写入16个字节的指令
   * @param val
   * @param id
   * @constructor
   */
  Send16Order(val, id) {
    let $str = val;
    let $str_ary = $str.split('');
    $str = "";
    $str_ary.forEach(($val, $index) => {
      $str += $val.charCodeAt().toString(16) + " "
    });
    $str = $str.substr(0, $str.length - 1)
    let $hexStr = "03 ff " + $str + ` ${id}`;

    this.WriteBufferInBle($hexStr, 16)
  },


  /**
   * todo 解析hex
   * @param hexStr
   * @param byte_count
   * @param sublen
   * @returns {string}
   * @constructor
   */
  DoAnalysis(hexStr, byte_count, sublen = 6) {
    //byte_count
    let $_str5 = hexStr.substr(sublen);
    let $datas = $_str5.substr(0, byte_count * 2);
    let $_data = "";
    for (let $i = 0; $i < $datas.length; $i += 2) {
      let $code = parseInt($datas.substr($i, 2), 16)
      $_data += String.fromCharCode($code)
    }
    return $_data;
  },

  /**
   * todo 清空当前脚本的变量值
   */
  clearLocalDatas() {
    control_close = false
    connect_toy = false;
    current_toy_id = "00";
    current_toy_UUID = "";
  },

  /**
   * todo 计算电量
   * @param $voltage
   * @returns {number}
   * @constructor
   */
  CalBLEPower($voltage) {
    let $max = 4100;
    let $min = 3500;

    //(当前电压值（mV）-最低电压值(mV)) / (最大电压值(mV)-最低电压值(mV)) *100%
    //当前电压
    let $_voltage = $voltage * 100;
    // console.log(`计算的当前电压:${$_voltage}`)

    let $percent = (($_voltage - $min) / ($max - $min)) * 100;
    // console.log(`计算的电量：${$percent}`);
    return $percent;
  },


  getNowTime() {
    var date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    const hour = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const millSeconds = date.getMilliseconds();

    return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
  },

  /**
   * 自动发送RF重连
   * @param  {Boolean} isOn    是否打开重连功能
   * @param  {[type]}  timeOut 有效时间
   * @return {[type]}          [description]
   * AA CC 03 00 01 0a d0 21
   */
  sendAutoConnectRf(isOn, timeOut) {
    let that = this;
    let onVal = isOn ? '01' : '00';
    let mTimeOut = timeOut.toString(16);

    if (mTimeOut.length == 1) {
      mTimeOut = `0${mTimeOut}`
    }

    let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
    this.WriteBufferInBle($hexStr)
  },

  /**
   * 打开原始数据
   * @constructor
   */
  SendOpenRawData() {
    this.SendOrder('04')
  },

  /**
   * 接收原始数据开关
   * @param status
   * @constructor
   */
  Send2BOrder(status = true) {
    let $hexStr = `03 00 00 01 2b`;
    if (!status) {
      $hexStr = `03 00 00 00 2b`;
    }
    this.WriteBufferInBle($hexStr)
  },

  /**
   * 打开原始数据
   * @constructor
   */
  SendCloseRawData() {
    this.SendOrder('05')
  },

  /**
   * 转移原始数据
   * @param buffer
   * @returns {*[]}
   */
  doOriginBufferToData(buffer) {
    let buffer_ary = []
    for (let i = 8; i < buffer.length; i += 2) {
      buffer_ary.push(parseInt(buffer.substr(i, 2), 16))
    }
    let _buffer_ary = buffer_ary.slice(0, buffer_ary.length - 2)
    let _buffer_16_ary = []
    for (let i = 0; i < _buffer_ary.length; i += 2) {
      let high = _buffer_ary[i];
      let low = _buffer_ary[i + 1]
      var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));
      _buffer_16_ary.push(this.hex2int(_firstNumber.toString(16)))
    }

    return _buffer_16_ary;
  },

  /**
   * 十六进制数转十进制
   * @param hexStr
   * @returns {number}
   */
  hex2int(hexStr) {
    let twoStr = parseInt(hexStr, 16).toString(2); // 将十六转十进制，再转2进制
    let bitNum = hexStr.length * 4; // 1个字节 = 8bit ，0xff 一个 "f"就是4位
    if (twoStr.length < bitNum) {
      while (twoStr.length < bitNum) {
        twoStr = "0" + twoStr;
      }
    }
    if (twoStr.substring(0, 1) == "0") {
      // 正数
      twoStr = parseInt(twoStr, 2); // 二进制转十进制
      return twoStr;
    } else {
      // 负数
      let twoStr_unsign = "";

      twoStr = parseInt(twoStr, 2) - 1; // 补码：(负数)反码+1，符号位不变；相对十进制来说也是 +1，但这里是负数，+1就是绝对值数据-1

      twoStr = twoStr.toString(2);
      twoStr_unsign = twoStr.substring(1, bitNum); // 舍弃首位(符号位)
      // 去除首字符，将0转为1，将1转为0   反码
      twoStr_unsign = twoStr_unsign.replace(/0/g, "z");
      twoStr_unsign = twoStr_unsign.replace(/1/g, "0");
      twoStr_unsign = twoStr_unsign.replace(/z/g, "1");

      twoStr = parseInt(-twoStr_unsign, 2);
      return twoStr;
    }
  }
};
