import { msg, back, showModal, go, loading } from "./traoAPI";
const app = getApp();
import { keywordTofilter } from "./util";
const log = require("./log");
import commandMap from "./commandMap";

export const getSystemInfo = () => {
  return new Promise((reslove, reject) => {
    wx.getSystemInfo({
      success(res) {
        reslove(res);
      },
    });
  });
};

export const openBluetoothAdapter = () => {
  return new Promise((reslove, reject) => {
    wx.openBluetoothAdapter({
      success(res) {
        reslove(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const startBluetoothDevicesDiscovery = () => {
  return new Promise((reslove, reject) => {
    wx.startBluetoothDevicesDiscovery({
      //开始搜索蓝牙
      allowDuplicatesKey: false,
      success(res) {
        reslove(res);
      },
      fail: function (err) {
        reject(err);
      },
    });
  });
};

export const createBLEConnection = (deviceId) => {
  return new Promise((reslove, reject) => {
    wx.createBLEConnection({
      deviceId,
      success(res) {
        reslove(res);
      },
      fail(error) {
        reject(error);
      },
    });
  });
};

export const closeBLEConnection = (deviceId) => {
  return new Promise((reslove, reject) => {
    wx.closeBLEConnection({
      deviceId,
      success(res) {
        reslove(res);
      },
      fail(error) {
        reslove(error);
        // reject(error)
      },
    });
  });
};

//数组下标1读取 0写入
export const getBLEDeviceServices = (deviceId) => {
  return new Promise((reslove, reject) => {
    wx.getBLEDeviceServices({
      //获取服务以及服务的uuid
      deviceId,
      success(res) {
        console.log("主要服务");
        console.log(res);
        let servicesuuid = res.services[0].uuid; //主要服务
        wx.getBLEDeviceCharacteristics({
          //获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
          deviceId,
          serviceId: servicesuuid,
          success(ress) {
            console.log(ress);
            let characteristicsuuid0 = ress.characteristics[0].uuid; //写入
            let characteristicsuuid1 = ress.characteristics[1].uuid; //读取
            reslove({
              servicesuuid,
              characteristicsuuid0,
              characteristicsuuid1,
            });
          },
          fail(err) {
            reject(err);
          },
        });
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const notifyBLECharacteristicValueChange = (info) => {
  return new Promise((reslove, reject) => {
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: info.deviceId,
      serviceId: info.servicesuuid,
      characteristicId: info.characteristicsuuid1,
      success(res) {
        reslove(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const writeBLECharacteristicValue = (info, completeCallback) => {
  return new Promise((reslove, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId: info.deviceId,
      serviceId: info.servicesuuid,
      characteristicId: info.characteristicsuuid0,
      value: string2buffer(keywordTofilter(info.value)),
      success(res) {
        //实时日志：记录发出的蓝牙指令
        log.info(commandMap.sendBLECommand, keywordTofilter(info.value));
        reslove(res);
        console.log(keywordTofilter(info.value) + "发送成功");
      },
      fail(err) {
        console.log(err);
        console.log(keywordTofilter(info.value) + "发送失败");
        log.error(commandMap.sendCommandFail, keywordTofilter(info.value));
        reject(err);
      },
      complete() {
        completeCallback && completeCallback();
      },
    });
  });
};

export const sendCommand = (info) => {
  return new Promise((reslove, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.deviceInfo.deviceId,
      serviceId: app.globalData.deviceInfo.servicesuuid,
      characteristicId: app.globalData.deviceInfo.characteristicsuuid0,
      value: info.value,
      success(res) {
        console.log(info.value);
        reslove(res);
      },
      fail(err) {
        reject(err);
        console.log(err);
      },
    });
  });
};

// 将字符串转换成ArrayBufer
const string2buffer = (str) => {
  let val = "";
  if (!str) return;
  let length = str.length;
  let index = 0;
  let array = [];
  while (index < length) {
    array.push(str.substring(index, index + 2));
    index = index + 2;
  }
  val = array.join(",");
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(
    val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    })
  ).buffer;
};
