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 "./wl200";
import { fr200BleCommand, fr200DeviceControlCommand } from "./fr200";

import { DeviceToolKit as DeviceToolKitWE100 } from "@flossom-npm/iot-translater-we100";
import { DeviceToolKit as DeviceToolKitFR200 } from "@flossom-npm/iot-translater";

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

const deviceToolKitInstanceFR200 = new DeviceToolKitFR200("FR200");
deviceToolKitInstanceFR200.setDebug(true);

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: [], //离线数据

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

      currentDeviceType: "", // 现在的设备类型： WE200 WL200 FR200，当设备为WL200时，它还可能是WE200
    };
  }

  async onLoad() {}
  componentDidMount() {
    // 只有非断开状态的弹窗才自动连接蓝牙
    if (!this.props.isDisconnect) {
      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({
      hasVersionInfo: false, // 重置已获取版本信息状态
      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) => {
      let model = this.props.deviceInfo.model; // 限制只匹配当前传入的设备类型
      // 匹配数组：先匹配到哪个连接哪个
      let tranType: string[] = [];
      // 判断条件随着设备的增加而增加
      if (model === "WL200") {
        tranType = ["WL200", "WE200", "WE100", "12CAA"];
      } else if (model === "FR200") {
        tranType = ["FR200"];
      }
      for (let i = 0; i < item.devices.length; i++) {
        let devicesName = item.devices[i].localName || item.devices[i].name;
        // 是否匹配可连接设备
        let isAvailable = tranType.some(
          (item) => devicesName && devicesName.indexOf(item) > -1
        );
        // 判断设备是否可连接
        if (item.devices[i].connectable && isAvailable) {
          // 如果是已连接WE200后，再次搜索，则只能连接WL200
          if (this.state.currentDeviceType === "WE200") {
            if (!devicesName.includes("12CAA")) {
              return;
            }
          }
          // 缓存当前连接设备名 可能是发箍或面罩
          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 { 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") {
            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);
      });
  }

  /**获取附属设备信息与设置当前设备名字*/
  getQueryMatchStatusAndSetName(value) {
    const { deviceInfo } = this.props;
    let querySubDeviceArrayBuffer: any = null;
    let jsonStatus: any = null;
    if (deviceInfo.model == "WL200") {
      if (this.isWL200()) {
        this.setState({ currentDeviceType: "WL200" });
        jsonStatus = deviceToolKitInstanceWL200.toJsonStatus(value);
        querySubDeviceArrayBuffer = deviceToolKitInstanceWL200.toBleCommand(
          bleCommandSamples.querySubDevice as any
        );
      } else {
        this.setState({ currentDeviceType: "WE200" });
        jsonStatus = deviceToolKitInstanceM01.toJsonStatus(value);
        querySubDeviceArrayBuffer = deviceToolKitInstanceM01.toBleCommand(
          bleCommandSamples.querySubDevice as any
        );
      }
    } else if (deviceInfo.model == "M01") {
      this.setState({ currentDeviceType: "M01" });
      jsonStatus = deviceToolKitInstanceM01.toJsonStatus(value);
      querySubDeviceArrayBuffer = deviceToolKitInstanceM01.toBleCommand(
        bleCommandSamples.querySubDevice as any
      );
    } else if (deviceInfo.model === "FR200") {
      // FR200 不需要查询子设备
      jsonStatus = deviceToolKitInstanceFR200.toJsonStatus(value);
      console.log("FR200 jsonStatus", jsonStatus);
      this.setState({ currentDeviceType: "FR200" });
    }
    // if (querySubDeviceArrayBuffer) this.sendQuerySubDevice(querySubDeviceArrayBuffer)
    return jsonStatus;
  }

  /** 7.通知BLE特征值更改  连接成功需拿到响应判断是否需要升级，然后跳转详情页 */
  notifyBLECharacteristicValueChange() {
    console.log("7.通知BLE特征值更改");
    const { 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 jsonStatus = this.getQueryMatchStatusAndSetName(value.value);
            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,
                      islian: true, // 不需要离线记录，但暂未完全删除这部分逻辑，所以直接设为true
                    });

                    this.detectVersionUpdate(); // 获取升级信息
                    // todo 连接成功需删除离线记录，暂时未缓存离线记录
                    if (this.state.connectionSuccess) return;
                  }
                  break;
                case "BleStatusSync": // 设备连接状态
                  console.log(
                    "设备连接状态jsonStatus.connectMessage",
                    jsonStatus.connectMessage
                  );
                  if (jsonStatus.connectMessage?.connectType == "CONNECTED") {
                    switch (jsonStatus.connectMessage?.deviceName) {
                      case OtaDeviceTypeEnum.WE100:
                        console.log("手环连上了 value => ", jsonStatus);
                      case OtaDeviceTypeEnum.FACIALMASK:
                        console.log("面膜连上了 value => ", jsonStatus);
                        this.detectVersionUpdate();
                        break;
                      case OtaDeviceTypeEnum.WL200:
                        console.log("面罩连上了 value => ", jsonStatus);
                        this.detectVersionUpdate();
                        break;
                      case "FR200":
                        console.log("FR200连上了 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);
              console.log("当前设备：", jsonStatus.otaDeviceType);
              console.log("当前设备版本号：", jsonStatus.versionNo);

              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("WE") > -1) {
                    latestVersionNo = deviceInfo.we200IotVersion;
                  }
                  // 判断版本号是否需要升级
                  const isNeedToUpdateBl = isNeedToUpdate(
                    deviceVersionNo,
                    latestVersionNo
                  );
                  console.log("isNeedToUpdateBl", isNeedToUpdateBl);
                  if (isNeedToUpdateBl) {
                    // 版本号需要更新: 告诉父级页面，关闭连接弹窗，显示更新弹窗
                    this.props.upgradeFun();
                  } else {
                    if (
                      currentDevicesName === "WE100" ||
                      currentDevicesName === "WE200"
                    ) {
                      console.log("closeBLEConnection");
                      setTimeout(() => {
                        this.againConnection();
                      }, 1000);
                      return;
                    }
                    console.log("不需要升级，跳转进入仪器详情页");
                    // 不需要升级，跳转进入仪器详情页
                    if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
                    this.pairingChange(this.state);
                  }
                  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(() => {
              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 { deviceInfo } = this.props;
    let model = deviceInfo.model;
    if (model == "WL200") {
      if (!this.isWL200()) {
        model = "WE200";
      }
    }

    const isWEorWL = ["WL200", "WE200", "WE100"].includes(model);
    const isFRDevice = ["FR200", "FR380", "FR390"].includes(model);
    if (isFRDevice) {
      if (model === "FR200") {
        const value = deviceToolKitInstanceFR200.toBleCommand(
          fr200BleCommand.InfoQuery.versionInfo as any
        );
        sendCommand({ value });
      } else {
        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 if (isWEorWL) {
      const versionCommand = {
        commandType: "InfoQuery",
        infoQueryType: "versionInfo",
        otaDeviceType: "",
      };
      if (this.isWL200()) {
        // WL200
        const otaDeviceType = OtaDeviceTypeEnum.WL200;
        versionCommand.otaDeviceType = otaDeviceType;
        const value = deviceToolKitInstanceWL200.toBleCommand(
          versionCommand as any
        );
        sendCommand({ value });
      } else {
        // WE200 WE100
        const otaDeviceType = OtaDeviceTypeEnum.WE100;
        versionCommand.otaDeviceType = otaDeviceType;
        const value = deviceToolKitInstanceM01.toBleCommand(
          versionCommand as any
        );
        sendCommand({ value });
      }
    }
  }

  /** 获取离线记录 */
  sendofflist() {
    if (this.state.offlineDataindex == this.state.offlineDataList.length) {
      console.log("离线记录获取完成", this.state);
      /****
       * 发送同步时间
       * ****/
      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("发送获取离线记录(细)指令");
    const { deviceInfo } = this.props;
    let model = deviceInfo.model;
    if (model === "FR200") {
      let matchArrayBuffer = deviceToolKitInstanceFR200.toBleCommand(
        fr200BleCommand.InfoQuery.clockDetail as any
      );
      sendCommand({ value: matchArrayBuffer });
    } else {
      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: [] }); // 置空重查离线记录

    const { deviceInfo } = this.props;
    let model = deviceInfo.model;
    if (model === "FR200") {
      let matchArrayBuffer = deviceToolKitInstanceFR200.toBleCommand(
        fr200BleCommand.InfoQuery.clockSummary as any
      );
      sendCommand({ value: matchArrayBuffer });
    } else {
      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 { deviceInfo } = this.props;
    console.log(commandMap.sendMatchCode, `仪器:${deviceInfo.model}发送匹配码`);
    let matchArrayBuffer: any = null;
    switch (deviceInfo.model) {
      case InstrumentTypeEnum.FR200:
        matchArrayBuffer = deviceToolKitInstanceFR200.toBleCommand(
          fr200BleCommand.match as any
        );
        break;
      case InstrumentTypeEnum.WL200:
        let currentDevicesName = getStorageSync("currentDevicesName");
        // 区分面罩和发箍
        if (currentDevicesName.indexOf("12CAA") > -1) {
          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);
        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 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);
          console.log("超时未返回版本号 this.pairingChange", this.state);
          this.pairingChange(this.state);
        } else {
          this.sendGetVersion();
        }
      }
    }, 600);

    // 5秒后没有收到版本返回，直接跳去护理页
    if (isGetVersionTimer) clearTimeout(isGetVersionTimer);
    isGetVersionTimer = setTimeout(() => {
      this.sendSyncRecording();
    }, 5000);
  }

  /** 发送同步记录 */
  sendSyncRecording() {
    const clockSummaryCommand = {
      commandType: "InfoQuery",
      infoQueryType: "offlineClockSummary",
    };

    const { deviceInfo } = this.props;
    let model = deviceInfo.model;
    if (model === "WL200") {
      if (!this.isWL200()) {
        model = "WE200";
      }
    }

    const isWEorWL = ["WL200", "WE200", "WE100"].includes(model);
    const isFRDevice = ["FR200", "FR380", "FR390"].includes(model);
    if (isFRDevice) {
      if (model === "FR200") {
        let value = deviceToolKitInstanceFR200.toBleCommand(
          fr200BleCommand.InfoQuery.clockSummary as any
        );
        sendCommand({ value }).then();
      }
    } else if (isWEorWL) {
      const value = this.isWL200()
        ? deviceToolKitInstanceWL200.toBleCommand(clockSummaryCommand as any)
        : deviceToolKitInstanceM01.toBleCommand(clockSummaryCommand 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.setState({
      isBreak: false,
      error: false,
      searchError: false,
      errorText: "",
    });
    setTimeout(() => {
      this.connection();
    });
    // this.props.confirm("confirm");
  };

  pairingChange = (data) => {
    console.log("pairingChange");
    let { currentDeviceType } = this.state;
    if (currentDeviceType !== "WE100" && currentDeviceType !== "WE200") {
      this.props.pairingChange(data);
    }
  };

  offlineChange = (data) => {
    console.log("offlineChange");
    let { currentDeviceType } = this.state;
    if (currentDeviceType !== "WE100" && currentDeviceType !== "WE200") {
      this.props.offlineChange(data);
    }
  };

  render() {
    let { isConnection, connectionSuccess, error, currentDeviceType } =
      this.state;
    let { deviceInfo, isDisconnect } = this.props;
    return (
      <Block>
        <DeviceConnectPopup
          close={this.onClose}
          confirm={this.onConfirm}
          reconnect={this.onReconnect}
          data={deviceInfo}
          isShow={true}
          currentDeviceType={currentDeviceType}
          connectionSuccess={connectionSuccess}
          isConnection={isConnection}
          error={error}
          isDisconnect={isDisconnect}
          title="面罩模式启动中"
        />
      </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);
