import Taro from "@tarojs/taro";
import classnames from "classnames";

import { Component, PropsWithChildren, useEffect, useState } from "react";
import { Block, View, Text, Image, Input, Button } from "@tarojs/components";

import DeviceConnectPopup from "../device-connection-popup/device-connection-popup";

/*** redux ***/
import { connect } from "react-redux";
import {
  setBluetoothInfo,
  setDeviceId,
} from "../../../store/features/deviceInfo";
/*** redux end ***/

import {
  getSystemInfo,
  openBluetoothAdapter,
  startBluetoothDevicesDiscovery,
  createBLEConnection,
  closeBLEConnection,
  getBLEDeviceServices,
  notifyBLECharacteristicValueChange,
  writeBLECharacteristicValue,
  sendCommand,
} from "@/utils/bluetoothWXAPI";
import {
  ab2hex,
  ccrc8,
  filterBleData,
  getofflineData,
  hex2int,
  getTimeCode,
  isNeedToUpdate,
} from "@/utils/util";
const log = require("@/utils/log");
import commandMap from "@/utils/commandMap";
import { bleCommandSamples } from "./test";

import { DeviceToolKit as DeviceToolKitWE100 } from "@flossom-npm/iot-translater-we100";
const deviceToolKitInstanceWL200 = new DeviceToolKitWE100("WL200", "WL200");
deviceToolKitInstanceWL200.setDebug(true);

// const _deviceToolKitInstanceWL200 = new DeviceToolKitWE100("WE100", "WL200");

const deviceToolKitInstanceM01 = new DeviceToolKitWE100("WE100", "M01");
deviceToolKitInstanceM01.setDebug(true);

const deviceToolKitInstanceFR200 = new DeviceToolKitFR200("FR200");

import { DeviceToolKit as DeviceToolKitFR200 } from "@flossom-npm/iot-translater";
import {
  showModal,
  msg,
  setStorageSync,
  getStorageSync,
} from "@/utils/traoAPI";

// const { InstrumentTypeEnum, OtaDeviceTypeEnum } = app.globalData;
import InstrumentTypeEnum from "../InstrumentTypeEnum";
import OtaDeviceTypeEnum from "../OtaDeviceTypeEnum";

// 定义一个变量，用于存放获取版本定时器
let isGetVersionTimer: any = null;
// 定义一个变量，用于存放获取子设备定时器
let isGetSubDeviceTimer: any = null;
// 定义一个变量，用于存放获取同步录制定时器
let isGetSyncRecordingTimer: any = null;

// 定义一个变量，用于存放超时定时器
let overTimer: any = null;

// 定义一个变量，用于存放获取子设备定时器次数
let isGetSubDeviceTimerNum = 0;

// 定义一个变量，用于存放发送获取版本定时器
let sendgetversionTimer: any = null;
// 定义一个变量，用于存放发送获取版本定时器次数
let sendGetVersionTimerNum = 0;

let searchBluetootTimers: any = null; // 搜索蓝牙定时器
let searchBluetootTimersNum = 15; // 搜索蓝牙秒数 15秒

let connectionTimer: any = null; // 连接蓝牙定时器
let connectionTimerNumber = 10000; // 连接蓝牙超时毫秒

let sendPairingTimer: any = null; // 发送配对

import "./index.less";

class ConnectionBluetoot extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "ConnectionBluetoot",
      stepList: [], //指引
      stepListIndex: 0,

      platform: "", //客户端平台
      connectionSuccess: false, //配对成功

      isConnection: false, //是否处理连接中
      error: false, //是否连接失败
      errorText: "", //失败文字
      searchError: false, //是否没有搜索到设备
      connectionStatus: false, //是否连接成功状态
      hasVersionInfo: false, // 是否已获得版本信息
      hasSyncRecord: false,
      subDeviceConnectedStatus: false, //子设备是否连接成功状态
      synchronousStatus: false, // 设备同步记录状态
      islian: false, //是否获取离线记录状态
      offlineData: [], //离线协议返送数据
      offlineDataindex: 0, //离线记录发送下标index
      versionInfo: {}, //版本号
      offlineDataList: [], //离线数据

      prefix: "12CAA", // WL200蓝牙搜索前缀

      // WL200匹配
      tranType: [
        "WE100", // 发箍
        "WE200", // 发箍
        "WL200", // 发箍
        "12CAA", // 面罩前缀名
      ],
    };
  }

  async onLoad() {}
  componentDidMount() {
    this.connection();
  }

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {}

  isWL200() {
    let currentDevicesName = getStorageSync("currentDevicesName");
    if (currentDevicesName.indexOf("12CAA") > -1) {
      return true;
    }
    return false;
  }

  close() {
    clearInterval(sendPairingTimer);
    clearInterval(sendgetversionTimer);
    clearTimeout(isGetVersionTimer);
    clearTimeout(isGetSyncRecordingTimer);
    if (overTimer) clearTimeout(overTimer);
    // 重新开始
    this.again();
    // 关闭弹窗
    this.onClose();
    Taro.closeBluetoothAdapter();
  }

  /** 关闭连接前：重置数据 */
  again() {
    this.setState({
      stepListIndex: 0,
      isConnection: false,
      error: false,
      errorText: "",
      connectionStatus: false,
      islian: false,
      offlineDataindex: 0,
      versionInfo: {},
      offlineDataList: [],
    });
  }

  /** 开始连接 */
  connection() {
    this.setState({
      isConnection: false,
    });
    //初始化 蓝牙连接
    this.bluetoothInit();
  }

  /** 重新连接 */
  // againConnection() {
  //   this.setState({
  //     connectionStatus: false,
  //     islian: false,
  //     error: false,
  //   });
  //   Taro.closeBluetoothAdapter({
  //     complete: () => {
  //       this.bluetoothInit();
  //     },
  //   });
  // }

  // skip() {
  //   this.setState({
  //     stepListIndex: this.state.stepList.length - 1,
  //     isConnection: true,
  //   });
  //   //初始化 蓝牙连接
  //   this.bluetoothInit();
  // }

  /**1.蓝牙初始化*/
  bluetoothInit() {
    searchBluetootTimersNum = 0;
    getSystemInfo().then((res) => {
      console.log(res);
      // bluetoothEnabled   蓝牙开关
      // locationEnabled    地理位置的系统开关
      // locationAuthorized 允许微信使用定位的开关
      let { locationEnabled, locationAuthorized, bluetoothEnabled } = res;
      const softwareProblem = [
        locationEnabled,
        locationAuthorized,
        bluetoothEnabled,
      ].every((item) => !item);
      if (softwareProblem) {
        let errorText = !bluetoothEnabled
          ? "检测到手机设置当中，微信的蓝牙访问授权未打开，请前往开启蓝牙授权"
          : "检测到手机设置当中，微信的定位访问授权未打开，请前往开启定位授权";
        //手机定位或者微信定位的开关没开启
        this.setState({
          error: true,
          searchError: false,
          errorText,
        });
      } else {
        Taro.closeBluetoothAdapter({
          complete: () => {
            this.openBluetoothAdapter();
          },
        });
      }
    });
  }

  /**2.打开蓝牙适配器*/
  openBluetoothAdapter() {
    openBluetoothAdapter()
      .then((res) => {
        console.log("openBluetoothAdapter res value =>", res);
        let { errno, errMsg } = res;
        if (errno == 0) {
          this.startBluetoothDevicesDiscovery();
        } else {
          this.errorCode(errno, errMsg);
        }
      })
      .catch((err) => {
        let { errno, errMsg } = err;
        if (errMsg == "openBluetoothAdapter:fail auth deny") {
          showModal({
            t2: "您的微信小程序设置中，蓝牙授权未开启",
            btn2text: "前往授权",
          })
            .then((res) => {
              this.close();
              Taro.openSetting();
            })
            .catch(() => {
              this.close();
            });
        } else {
          console.log("openBluetoothAdapter err value => ", err);
          this.failErrorCode(errno, errMsg);
        }
      });
  }

  /** 3.开始蓝牙设备搜索 */
  startBluetoothDevicesDiscovery() {
    startBluetoothDevicesDiscovery()
      .then((res) => {
        let { errno, errMsg } = res;
        console.log("startBluetoothDevicesDiscovery res value=>", res);
        if (errno == 0) {
          /**
           * 开始搜索蓝牙
           * 设定8秒搜索时间，15秒后表示搜索不到 弹出
           */
          this.onBluetoothDeviceFound();
          searchBluetootTimers = setInterval(() => {
            searchBluetootTimersNum += 1;
            console.log(
              "searchBluetootTimersNum value => ",
              searchBluetootTimersNum
            );
            if (searchBluetootTimersNum === 15) {
              clearInterval(searchBluetootTimers);
              this.setState({
                error: true,
                searchError: true,
              });
            }
          }, 1000);
        } else {
          this.errorCode(errno, errMsg);
        }
      })
      .catch((err) => {
        let { errno, errMsg } = err;
        console.log("startBluetoothDevicesDiscovery error =>", err);
        this.failErrorCode(errno, errMsg);
      });
  }
  /** 4.蓝牙查找 */
  onBluetoothDeviceFound() {
    Taro.onBluetoothDeviceFound((item: any) => {
      console.log("蓝牙查找item", item, item.devices[0].name);
      console.info("搜索到到蓝牙设备 value => ", item.devices[0]?.name);
      console.log(">>>>>>>当前传入设备类型>>>>>", this.props.yiqiInfo.model);
      // 先匹配到哪个连接哪个
      let tranType = [
        this.props.yiqiInfo.model, // 当前传入设备类型
        ...this.state.tranType,
      ];
      for (let i = 0; i < item.devices.length; i++) {
        let devicesName = item.devices[i].localName || item.devices[i].name;
        console.log("devicesName", devicesName);
        console.log("tranType", tranType);
        // 是否匹配可连接设备
        let isAvailable = tranType.some(
          (item) => devicesName && devicesName.indexOf(item) > -1
        );
        console.log("isAvailable", isAvailable);
        // 判断设备是否可连接
        if (item.devices[i].connectable && isAvailable) {
          // 缓存当前连接设备名 可能是发箍或面罩
          setStorageSync("currentDevicesName", devicesName);
          console.log("连接的设备信息", item.devices[i], devicesName);

          let params = {
            deviceId: item.devices[i].deviceId,
          };
          this.props.setDeviceId(params); // 设置蓝牙连接设备ID

          setTimeout(() => {
            clearInterval(searchBluetootTimers);
            Taro.stopBluetoothDevicesDiscovery(); //停止搜索蓝牙
            this.createBLEConnection();
          }, 10);
          break;
        }
      }
    });
  }

  /** 5.新建蓝牙连接 */
  async createBLEConnection() {
    console.log("========新建蓝牙连接========");
    this.setState({ isConnection: true }); // 开始蓝牙连接
    try {
      await closeBLEConnection(this.props.bluetoothInfo.deviceId);
    } catch (e) {}
    clearTimeout(connectionTimer);
    const { yiqiInfo: deviceInfo } = this.props;
    /*********开始主动连接*******/
    createBLEConnection(this.props.bluetoothInfo.deviceId)
      .then((res) => {
        console.log("createBLEConnection", res);
        let { errno, errMsg } = res;
        if (errno == 0) {
          if (deviceInfo.model === "WL200") {
            this.setState({
              connectionStatus: true,
            });
            connectionTimer = setTimeout(() => {
              if (!this.state.islian) {
                if (overTimer) clearTimeout(overTimer);
                this.failErrorCode(-1, "连接蓝牙失败，请重新开机后重试");
              }
            }, connectionTimerNumber);
          }
          this.getBLEDeviceServices(); //获取特征
        } else {
          this.errorCode(errno, errMsg);
        }
      })
      .catch((err) => {
        let { errno, errMsg } = err;
        console.log("createBLEConnection error =>", err);
        this.failErrorCode(errno, errMsg);
      });
  }

  /** 6.获取蓝牙特征值 */
  getBLEDeviceServices() {
    console.log("========6.获取蓝牙特征值========");
    getBLEDeviceServices(this.props.bluetoothInfo.deviceId)
      .then((res) => {
        console.log("特征值", res);
        let params = {
          deviceId: this.props.bluetoothInfo.deviceId,
          servicesuuid: res.servicesuuid,
          characteristicsuuid1: res.characteristicsuuid1,
          characteristicsuuid0: res.characteristicsuuid0,
        };

        console.log("getBLEDeviceServices", params);
        // 获取并修改蓝牙特征值
        this.props.setBluetoothInfo(params);

        setTimeout(() => {
          this.notifyBLECharacteristicValueChange();
        }, 10);
      })
      .catch((err) => {
        let { errno, errMsg } = err;
        console.log("getBLEDeviceServices error =>", err);
        this.failErrorCode(errno, errMsg);
      });
  }

  /** 7.通知BLE特征值更改 */
  notifyBLECharacteristicValueChange() {
    console.log("7.通知BLE特征值更改");
    const { yiqiInfo: deviceInfo } = this.props;
    const bluetoothInfo = this.props.bluetoothInfo;
    notifyBLECharacteristicValueChange({
      deviceId: bluetoothInfo.deviceId,
      servicesuuid: bluetoothInfo.servicesuuid,
      characteristicsuuid1: bluetoothInfo.characteristicsuuid1,
      characteristicsuuid0: bluetoothInfo.characteristicsuuid0,
    })
      .then((ress) => {
        let { errno, errMsg } = ress;
        if (errno == 0) {
          // 订阅特征码变化
          Taro.onBLECharacteristicValueChange((value) => {
            // 配对成功进入？
            console.log("onBLECharacteristicValueChange value => ", value);
            let str = ab2hex(value.value); //转为16进制字符串
            console.log("转为16进制字符串 str", str);

            let connectionStatus = [
              "FR200",
              "WL200",
              "FR380",
              "FR390",
              "M01",
            ].includes(deviceInfo.model);

            let jsonStatus: any = null;
            let querySubDeviceArrayBuffer;

            if (deviceInfo.model == "WL200") {
              if (this.isWL200()) {
                jsonStatus = deviceToolKitInstanceWL200.toJsonStatus(
                  value.value
                );
                querySubDeviceArrayBuffer =
                  deviceToolKitInstanceWL200.toBleCommand(
                    bleCommandSamples.querySubDevice as any
                  );
              } else {
                jsonStatus = deviceToolKitInstanceM01.toJsonStatus(value.value);
                querySubDeviceArrayBuffer =
                  deviceToolKitInstanceM01.toBleCommand(
                    bleCommandSamples.querySubDevice as any
                  );
              }
            } else if (deviceInfo.model == "M01") {
              jsonStatus = deviceToolKitInstanceM01.toJsonStatus(value.value);
              querySubDeviceArrayBuffer = deviceToolKitInstanceM01.toBleCommand(
                bleCommandSamples.querySubDevice as any
              );
            }
            console.log(
              commandMap.reciviedBLECommand,
              `仪器模式: ${deviceInfo.model}`,
              jsonStatus
            );
            console.log("jsonStatus", jsonStatus);
            if (jsonStatus?.commandType === "BleMatch") {
              switch (jsonStatus?.bleCommandType) {
                case "SendMatchCode":
                  if (jsonStatus.matchedSuccess) {
                    console.log("BleMatch蓝牙配对成功");
                    clearInterval(sendPairingTimer);
                    if (overTimer) clearTimeout(overTimer);
                    this.setState({
                      connectionSuccess: true,
                      connectionStatus,
                      islian: true, // 不需要离线记录，但暂未完全删除这部分逻辑，所以直接设为true
                    });

                    // this.pairingChange(this.state); // 临时添加，用于跳转
                    this.detectVersionUpdate(); // 获取升级信息
                    // todo 连接成功需删除离线记录，暂时未缓存离线记录
                    if (this.state.connectionSuccess) return;
                    // 暂时不需要查询是否连接子设备, 直接进入查询版本信息
                    // this.detectVersionUpdate();
                    /*if(deviceInfo.type == instrumentTypeEnum.M01) {
                      this.detectVersionUpdate()
                    } else {
                      this.sendQuerySubDevice(querySubDeviceArrayBuffer)
                    }*/
                  }
                  break;
                case "BleStatusSync": // 设备连接状态
                  if (jsonStatus.connectMessage?.connectType == "CONNECTED") {
                    switch (jsonStatus.connectMessage?.deviceName) {
                      case OtaDeviceTypeEnum.WE100:
                      case OtaDeviceTypeEnum.FACIALMASK:
                        console.log("面膜连上了 value => ", jsonStatus);
                        this.detectVersionUpdate();
                        break;
                      case OtaDeviceTypeEnum.WL200:
                        console.log("面罩连上了 value => ", jsonStatus);
                        this.detectVersionUpdate();
                        break;
                      default:
                        break;
                    }
                  }
                  console.log("BleStatusSync value => ", jsonStatus);
                  break;
                case "QueryMatchStatus":
                  console.log("QueryMatchStatus value => ", jsonStatus);
                  break;
                default:
                  break;
              }
            } else if (jsonStatus?.commandType === "InfoQuery") {
              console.log("查询版本信息", jsonStatus);
              switch (jsonStatus.infoQueryType) {
                case "versionInfo":
                  if (this.state.hasVersionInfo) return;
                  clearTimeout(isGetVersionTimer);
                  this.setState({
                    hasVersionInfo: true, // 已返回版本信息
                    connectionStatus: true,
                    subDeviceConnectedStatus: true,
                    synchronousStatus: true,
                  });

                  let currentDevicesName = getStorageSync("currentDevicesName");
                  let deviceVersionNo = jsonStatus.versionNo;
                  let latestVersionNo = deviceInfo.iotVersion;
                  if (currentDevicesName.indexOf("12CAA") < -1) {
                    latestVersionNo = deviceInfo.we200IotVersion;
                  }
                  const isNeedToUpdateBl = isNeedToUpdate(
                    deviceVersionNo,
                    latestVersionNo
                  );
                  console.log("deviceInfo", deviceInfo);
                  console.log("isNeedToUpdateBl", isNeedToUpdateBl);
                  if (isNeedToUpdateBl) {
                    // 版本号需要更新，显示更新弹窗
                    this.props.upgradeFun();
                  }

                  // 判断是否需要升级
                  // M01和WL200 不需要在这里进行蓝牙更新
                  // if (isNeedToUpdateBl) {
                  // const pages = getCurrentPages();
                  // const matchPageList = [{
                  //   route: 'pages/MatrixWL200/pages/index/index'
                  // },{
                  //   route: 'pages/MatrixM01/pages/index/index'
                  // }];
                  // const hadOpen = checkSameKey(pages, matchPageList, 'route');
                  // if (!hadOpen) {
                  // this.triggerEvent("pairingChange", { deviceVersionNo });
                  // this.pairingChange({ deviceVersionNo });
                  // }
                  // } else {
                  //   this.sendSyncRecording()
                  // }
                  break;
                case "offlineClockSummary":
                  clearTimeout(isGetSyncRecordingTimer);
                  if (this.state.hasSyncRecord) return;
                  this.setState({
                    hasSyncRecord: true,
                    synchronousStatus: true,
                  });
                  console.log(
                    "离线汇总offlineClockSummary value =>",
                    jsonStatus
                  );
                // this.triggerEvent("pairingChange", this.state);
                // this.pairingChange(this.state);
                // TODO 查询离线记录结果
                default:
                  break;
              }
            }
          });
          /**
           * 是否需要获取离线记录和版本获取
           * 这里增加判断，类型不同识别的设备名称不一样
           * type1 FR200
           * type2 WM100
           * type3 we100
           * type4 FR380
           */
          console.log("发送配对码", deviceInfo.model);
          if (deviceInfo.model == "FR200") {
            if (sendPairingTimer) clearInterval(sendPairingTimer);
            sendPairingTimer = setInterval(() => {
              this.sendPairingSignal();
            }, 1000);
          } else if (deviceInfo.model == "WL200" || deviceInfo.model == "M01") {
            if (sendPairingTimer) clearInterval(sendPairingTimer);
            sendPairingTimer = setInterval(() => {
              console.log("test WL200");
              this.sendPairingSignal();
            }, 1000);
          } else if (
            deviceInfo.model == "FR380" ||
            deviceInfo.model == "FR390"
          ) {
            if (sendPairingTimer) clearInterval(sendPairingTimer);
            sendPairingTimer = setInterval(() => {
              this.sendPairingSignal();
            }, 1000);
          }
          if (overTimer) clearTimeout(overTimer);
          overTimer = setTimeout(() => {
            if (this.state.islian) {
              console.log("超时跳转护理页");
              // log.info("超时跳转护理页");
              // 已配对成功，其它操作导致超时未跳转则直接跳转
              // this.triggerEvent("offlineChange", this.state);
              this.offlineChange(this.state);
              return;
            }
            if (sendPairingTimer) clearInterval(sendPairingTimer);
            this.failErrorCode(1509005, "配对超时");
          }, 1000 * 15);
        } else {
          this.errorCode(errno, errMsg);
        }
      })
      .catch((err) => {
        console.log("notifyBLECharacteristicValueChange error =>", err);
        let { errno, errMsg } = err;
        this.failErrorCode(errno, errMsg);
      });
  }

  // 8.发送指令：获取仪器版本号
  sendGetVersion() {
    const { yiqiInfo: deviceInfo } = this.props;
    const isFRDevice = ["FR200", "FR380", "FR390"].includes(deviceInfo.model);
    // log.info(commandMap.sendVersionCommand, `仪器:${deviceInfo.model}`);
    console.log(commandMap.sendVersionCommand, `仪器:${deviceInfo.model}`);
    if (isFRDevice) {
      writeBLECharacteristicValue({
        //发送获取仪器版本号
        deviceId: this.props.bluetoothInfo.deviceId,
        servicesuuid: this.props.bluetoothInfo.servicesuuid,
        characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
        characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
        value: `dbf0a00300${ccrc8("dbf0a00300")}de`,
      });
    } else {
      const otaDeviceType = this.isWL200()
        ? OtaDeviceTypeEnum.WL200
        : OtaDeviceTypeEnum.WE100;
      const versionCommand = {
        commandType: "InfoQuery",
        infoQueryType: "versionInfo",
        otaDeviceType,
      };
      console.log("versionCommand", versionCommand);

      // 区分WL200 和 发箍
      const value = this.isWL200()
        ? deviceToolKitInstanceWL200.toBleCommand(versionCommand as any)
        : deviceToolKitInstanceM01.toBleCommand(versionCommand as any);
      sendCommand({ value });
    }
  }

  /** 获取离线记录 */
  sendofflist() {
    // log.info()
    if (this.state.offlineDataindex == this.state.offlineDataList.length) {
      console.log("离线记录获取完成", this.state);
      // log.info(commandMap.finishOfflineData, this.state.offlineDataList);
      /****
       * 发送同步时间
       * ****/
      this.sendAsyncTime();
      console.log(this.state.offlineDataList);
      console.log("版本号:" + this.state.versionInfo.version);
      this.setState({ islian: true });
      clearTimeout(connectionTimer);
      this.offlineChange(this.state);
      return false;
    }
    console.log("发送获取离线记录(细)指令");
    // log.info(commandMap.finishOfflineData, "发送获取离线记录(细)指令");
    writeBLECharacteristicValue({
      //发送获取离线记录
      deviceId: this.props.bluetoothInfo.deviceId,
      servicesuuid: this.props.bluetoothInfo.servicesuuid,
      characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
      characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
      value: this.state.offlineData[this.state.offlineDataList.length],
    });
  }
  /** 获取离线记录(汇总) */
  sendofflistSummary() {
    let str = "DBF0A00200";
    console.log("发送离线记录汇总指令 ==》", str);
    this.setState({ offlineDataList: [] }); // 置空重查离线记录
    // log.info(commandMap.finishOfflineData, `发送获取离线记录(总)指令`);
    writeBLECharacteristicValue({
      //发送获取离线记录
      deviceId: this.props.bluetoothInfo.deviceId,
      servicesuuid: this.props.bluetoothInfo.servicesuuid,
      characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
      characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
      value: `${str}${ccrc8(str)}DE`,
    });
  }

  /** 9.发送配对码 */
  sendPairingSignal() {
    console.log("9.发送配对码 sendPairingSignal");
    const { yiqiInfo: deviceInfo } = this.props;
    // log.info(commandMap.sendMatchCode, `仪器:${deviceInfo.model}发送匹配码`);
    console.log(commandMap.sendMatchCode, `仪器:${deviceInfo.model}发送匹配码`);
    let matchArrayBuffer: any = null;
    switch (deviceInfo.model) {
      case InstrumentTypeEnum.FR200:
        matchArrayBuffer = deviceToolKitInstanceFR200.toBleCommand(
          bleCommandSamples.match as any
        );
        break;
      case InstrumentTypeEnum.WL200:
        console.log("正在发送WL200", bleCommandSamples.match);
        let currentDevicesName = getStorageSync("currentDevicesName");
        // 区分面罩和发箍
        if (currentDevicesName.indexOf("12CAA") > -1) {
          console.log("12CAA");
          matchArrayBuffer = deviceToolKitInstanceWL200.toBleCommand(
            bleCommandSamples.match as any
          );
        } else {
          matchArrayBuffer = deviceToolKitInstanceM01.toBleCommand(
            bleCommandSamples.match as any
          );
        }

        break;
      case InstrumentTypeEnum.FR380:
        writeBLECharacteristicValue({
          deviceId: this.props.bluetoothInfo.deviceId,
          servicesuuid: this.props.bluetoothInfo.servicesuuid,
          characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
          characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
          value: `DBF0A8010C464C534D204D465233383000E8DE`,
        });
        break;
      case InstrumentTypeEnum.FR390:
        writeBLECharacteristicValue({
          deviceId: this.props.bluetoothInfo.deviceId,
          servicesuuid: this.props.bluetoothInfo.servicesuuid,
          characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
          characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
          value: `DBF0A8010C464C534D204D46523339300043DE`,
        });
        break;
      case InstrumentTypeEnum.M01:
        matchArrayBuffer = deviceToolKitInstanceM01.toBleCommand(
          bleCommandSamples.match as any
        );
        break;
      default:
        break;
    }
    if (matchArrayBuffer) console.log("matchArrayBuffer", matchArrayBuffer);
    sendCommand({ value: matchArrayBuffer })
      .then((res) => {
        console.log("matchArrayBuffer res", res);
      })
      .catch((e) => {
        // 下发配对指令失败，走重连操作
        clearInterval(sendPairingTimer);
        // wx.closeBLEConnection();
        this.createBLEConnection();
      });
  }

  /** 同步时间 */
  sendAsyncTime() {
    console.log("同步时间");
    writeBLECharacteristicValue({
      //发送同步时间
      deviceId: this.props.bluetoothInfo.deviceId,
      servicesuuid: this.props.bluetoothInfo.servicesuuid,
      characteristicsuuid1: this.props.bluetoothInfo.characteristicsuuid1,
      characteristicsuuid0: this.props.bluetoothInfo.characteristicsuuid0,
      value: getTimeCode(),
    });
  }

  /** 错误代码处理 */
  errorCode(errno, errMsg) {
    clearInterval(searchBluetootTimers);
    clearInterval(sendgetversionTimer);
    // console.info("errorCode err => ", errno, errMsg);
    if (errno == 10001 || errno == 10009) {
      let t2 =
        errno == 10001
          ? "您的手机蓝牙适配器不可用，请联系微信顾问"
          : "你的Android 系统版本低于4.3不支持蓝牙连接";
      this.close();
      setTimeout(() => {
        showModal({
          t2,
          showCancel: false,
          btn2text: "知道了",
        }).then(() => {
          this.close();
        });
      }, 500);
      return;
    }
    let errorText = "";
    switch (errno) {
      case -1:
        errorText = "已连接";
        break;
      case 10000:
        errorText = "未初始化蓝牙适配器";
        break;
      case 10000:
        errorText = "未初始化蓝牙适配器";
        break;
      case 10001:
        errorText = "当前蓝牙适配器不可用";
        break;
      case 10002:
        errorText = "没有找到指定设备";
        break;
      case 10003:
        errorText = "连接失败";
        break;
      case 10004:
        errorText = "没有找到指定服务";
        break;
      case 10005:
        errorText = "没有找到指定特征";
        break;
      case 10006:
        errorText = "当前连接已断开";
        break;
      case 10007:
        errorText = "当前特征不支持此操作";
        break;
      case 10008:
        errorText = "其余所有系统上报的异常";
        break;
      case 10009:
        errorText = "其余所有系统上报的异常";
        break;
      case 10012:
        errorText = "连接超时";
        break;
      case 10013:
        errorText = "连接 deviceId 为空或者是格式不正确";
        break;
      default:
        errorText = errMsg;
        break;
    }
    this.setState({
      error: true,
      searchError: false,
      errorText,
    });
  }

  failErrorCode(errno, errMsg) {
    console.log("failErrorCode err => ", errno, errMsg);
    clearInterval(searchBluetootTimers);
    clearInterval(sendgetversionTimer);
    // log.info("连接仪器失败", errno, errMsg);
    console.log("连接仪器失败", errno, errMsg);
    let errorText = "";
    switch (errno) {
      case 1500101:
        errorText = "未初始化蓝牙适配器";
        break;
      case 1500102:
        errorText = "微信无法使用蓝牙，请到系统设置中启用";
        break;
      case 1500103:
        errorText = "当前蓝牙设备获取不到Service/获取不到对应UUID的Service";
        break;
      case 1500104:
        errorText = "调用系统蓝牙能力失败, 详细错误见errMsg";
        break;
      case 1500105:
        errorText = "系统不支持BLE";
        break;
      case 1510101:
        errorText = "配对当前蓝牙设备需要pin码";
        break;
      case 1510102:
        errorText = "支持蓝牙后台通信的设备数目已经达到上限";
        break;
      case 1509001:
        errorText = "连接蓝牙设备失败";
        break;
      case 1509003:
        errorText = "未连接上该蓝牙设备";
        break;
      case 1509005:
        errorText = "蓝牙操作超时";
        break;
      case 1509007:
        errorText = "当前蓝牙设备已经连接上";
        break;
      case 1509008:
        errorText = "Android6.0以上, 蓝牙扫描需授权地理位置";
        break;
      default:
        errorText = errMsg;
    }
    this.setState({
      error: true,
      searchError: false,
      errorText,
    });
  }
  sendQuerySubDevice(value) {
    isGetSubDeviceTimer = setInterval(() => {
      sendCommand({ value });
      isGetSubDeviceTimerNum += 1;
      // 15秒超时
      if (isGetSubDeviceTimerNum === 15) {
        this.closeQuerySubDevice();
        this.setState({
          error: true,
          searchError: true,
        });
      }
    }, 1000);
  }
  closeQuerySubDevice() {
    clearInterval(isGetSubDeviceTimer);
    isGetSubDeviceTimerNum = 0;
  }
  // 获取版本信息
  detectVersionUpdate() {
    this.closeQuerySubDevice();
    this.sendGetVersion(); // 获取版本信息
    sendGetVersionTimerNum = 0;
    // 600毫秒查询一次版本号是否返回，若返回则跳转护理页
    if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
    isGetVersionTimer = setInterval(() => {
      if (this.state.hasVersionInfo) {
        if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
      } else {
        sendGetVersionTimerNum += 1;
        if (sendGetVersionTimerNum >= 10) {
          // 超时未返回版本号
          if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
          this.setState({
            connectionStatus: true,
          });
          console.log("超时未返回版本号 this.pairingChange", this.state);
          // this.pairingChange(this.state);
        } else {
          this.sendGetVersion();
        }
      }
    }, 600);

    // 5秒后没有收到版本返回，直接跳去护理页
    // if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
    //    isGetVersionTimer = setTimeout(() => {
    //      that.setData({
    //        connectionStatus: true,
    //        // subDeviceConnectedStatus: true, // 子设备连接状态
    //      })
    //      this.sendSyncRecording()
    //    }, 5000);
  }

  /** 发送同步记录 */
  sendSyncRecording() {
    const { yiqiInfo: deviceInfo } = this.props;
    const versionCommand = {
      commandType: "InfoQuery",
      infoQueryType: "offlineClockSummary",
    };
    const value = this.isWL200()
      ? deviceToolKitInstanceWL200.toBleCommand(versionCommand as any)
      : deviceToolKitInstanceM01.toBleCommand(versionCommand as any);
    sendCommand({ value }).then();
    if (isGetSyncRecordingTimer) clearTimeout(isGetSyncRecordingTimer);
    isGetSyncRecordingTimer = setTimeout(() => {
      if (this.state.hasSyncRecord) {
        if (isGetSyncRecordingTimer) clearTimeout(isGetSyncRecordingTimer);
      } else {
        this.sendSyncRecording();
      }
    }, 1000);
  }

  onClose = () => {
    this.props.close();
  };

  onConfirm = () => {
    this.props.confirm("confirm");
  };

  onReconnect = () => {
    console.log("onReconnect");
    // this.props.confirm("confirm");
  };

  pairingChange = (data) => {
    this.props.pairingChange(data);
  };

  offlineChange = (data) => {
    this.props.offlineChange(data);
  };

  render() {
    let { name, isConnection, connectionStatus, connectionSuccess, error } =
      this.state;
    let { yiqiInfo } = this.props;
    return (
      <Block>
        <DeviceConnectPopup
          close={this.onClose}
          confirm={this.onConfirm}
          reconnect={this.onReconnect}
          data={yiqiInfo}
          isShow={true}
          // connectionStatus={connectionStatus}
          connectionSuccess={connectionSuccess}
          isConnection={isConnection}
          error={error}
          title="面罩模式启动中"
        />
        <View>{name}</View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  bluetoothInfo: state.deviceInfo.bluetoothInfo,
});
const mapDispatchToProps = (dispatch) => ({
  setBluetoothInfo(data) {
    dispatch(setBluetoothInfo(data));
  },
  setDeviceId(data) {
    dispatch(setDeviceId(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(ConnectionBluetoot);
