import { msg, back, showModal, go, loading } from "./traoAPI";

export const getSystemInfo = () => {
  return new Promise((reslove, reject) => {
    wx.getSystemInfo({
      success(res) {
        let gps = res.locationEnabled;
        if (!gps) {
          showModal({
            t1: "请打开GPS定位",
            t2: "不打开GPS定位，可能无法搜索到蓝牙设备",
            btn1show: false,
          });
        } else {
          reslove();
        }
      },
    });
  });
};

export const openBluetoothAdapter = () => {
  return new Promise((reslove, reject) => {
    wx.openBluetoothAdapter({
      success(res) {
        reslove();
      },
      fail(res) {
        wx.showToast({
          title: "请检查手机蓝牙是否打开",
          icon: "none",
        });
        reject();
      },
    });
  });
};

export const startBluetoothDevicesDiscovery = () => {
  return new Promise((reslove, reject) => {
    wx.startBluetoothDevicesDiscovery({
      //开始搜索蓝牙
      allowDuplicatesKey: false,
      success(res) {
        reslove();
      },
      fail: function (res) {
        if (res.errno == 1500104 && res.errCode == 10008) {
          return showModal({
            t2: "连接过于频繁，请稍后再试！",
            btn1show: false,
          });
        }
        if (res.errno == 1509008) {
          return showModal({
            t2: "请打开定位，在重新连接",
            btn1show: false,
          });
        }
        showModal({
          t1: "startBluetoothDevicesDiscovery失败",
          t2: JSON.stringify(res),
          btn1show: false,
        });
      },
    });
  });
};

export const createBLEConnection = (deviceId) => {
  return new Promise((reslove, reject) => {
    wx.createBLEConnection({
      deviceId,
      success(res) {
        if (res.errCode == 0) {
          reslove(res);
        } else if (res.errCode == 10013) {
          showModal({
            t2: "连接 deviceId 为空或者是格式不正确",
            btn1show: false,
          });
        } else if (res.errCode == 10012) {
          showModal({
            t2: "当前 BLE 设备已经连接上",
            btn1show: false,
          });
        } else if (res.errCode == 10009) {
          showModal({
            t2: "Android 系统特有，系统版本低于 4.3 不支持 BLE",
            btn1show: false,
          });
        } else if (res.errCode == 10008) {
          showModal({
            t2: "其余所有系统上报的异常",
            btn1show: false,
          });
        } else if (res.errCode == 10007) {
          showModal({
            t2: "当前特征不支持此操作",
            btn1show: false,
          });
        } else if (res.errCode == 10006) {
          showModal({
            t2: "当前连接已断开",
            btn1show: false,
          });
        } else if (res.errCode == 10005) {
          showModal({
            t2: "没有找到指定特征",
            btn1show: false,
          });
        } else if (res.errCode == 10004) {
          showModal({
            t2: "没有找到指定服务",
            btn1show: false,
          });
        } else if (res.errCode == 10003) {
          showModal({
            t2: "连接失败",
            btn1show: false,
          });
        } else if (res.errCode == 10002) {
          showModal({
            t2: "没有找到指定设备",
            btn1show: false,
          });
        } else if (res.errCode == 10001) {
          showModal({
            t2: "当前蓝牙适配器不可用",
            btn1show: false,
          });
        } else if (res.errCode == 10000) {
          showModal({
            t2: "未初始化蓝牙适配器",
            btn1show: false,
          });
        } else if (res.errCode == -1) {
          showModal({
            t2: "已连接",
            btn1show: false,
          });
        }
      },
      fail(error) {
        if (error.errno == "1509007") {
          showModal({
            t2: "当前 BLE 设备已经连接上",
            btn1show: false,
          });
        }
        if (error.errno == "1509005") {
          showModal({
            t2: "BLE操作超时",
            btn1show: false,
          });
        }
        if (error.errno == "1509006") {
          showModal({
            t2: "未找到设备",
            btn1show: false,
          });
        }
        if (error.errno == "1509001") {
          showModal({
            t2: "连接 BLE 设备失败",
            btn1show: false,
          });
        }
        if (error.errno == "1509008") {
          showModal({
            t2: "Android6.0以上, BLE扫描需授权地理位置",
            btn1show: false,
          });
        }
        if (error.errno == "1510102") {
          showModal({
            t2: "支持蓝牙后台通信的设备数目已经达到上限",
            btn1show: false,
          });
        }
      },
    });
  });
};

//数组下标1读取 0写入
export const getBLEDeviceServices = (deviceId) => {
  return new Promise((reslove, reject) => {
    wx.getBLEDeviceServices({
      //获取服务以及服务的uuid
      deviceId,
      success(res) {
        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) {
            console.log(err);
          },
        });
      },
      fail(err) {
        console.log(err);
      },
    });
  });
};

export const notifyBLECharacteristicValueChange = (info) => {
  console.log(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) {
        console.log(err);
      },
    });
  });
};

export const writeBLECharacteristicValue = (info) => {
  return new Promise((reslove, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId: info.deviceId,
      serviceId: info.servicesuuid,
      characteristicId: info.characteristicsuuid0,
      value: string2buffer(info.value),
      success(res) {
        reslove(res);
        console.log(info.value + "发送成功");
      },
      fail(err) {
        console.log(err);
        console.log(info.value + "发送失败");
      },
    });
  });
};

// 将字符串转换成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;
};
