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

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

/*** redux ***/
import { connect } from "react-redux";
/*** redux end ***/

/* 公共组件 */
import Navbar from "@/components/navbar/navbar";
import PopupCountdown from "@/components/popup/popup-countdown";
import PopupStepTips from "@/components/popup/popup-step-tips";
import PopupConfirm from "@/components/popup/popup-confirm";
/* 公共组件 END */

/* 本页组件 */
import ElectricityView from "./components/ElectricityView/index";
import ModeListView from "./components/ModeList/index";
import ModeContent from "./components/ModeContent/index";
import Footer from "./components/Footer";
/* 本页组件 END */

import { getStorageSync, setStorageSync } from "@/utils/traoAPI";
import { InstrumentInfo } from "@/utils/Interface";
import "./iotCarePlan.less";

// import log from "@/utils/log";
// log.info("123456info", 123456, { sdfasdf: 123 });

import {
  notifyBLECharacteristicValueChange,
  sendCommand,
} from "@/utils/bluetoothWXAPI";
import {
  deviceCommandSamples,
  bleCommandSamples,
} from "@/components/bluetoot/connection/test";
import {
  s_to_s,
  s_to_m,
  minSecToS,
  s_to_ms,
  isNeedToUpdate,
} from "@/utils/util";
import { DeviceToolKit as DeviceToolKitWE100 } from "@flossom-npm/iot-translater-we100";
import commandMap from "@/utils/commandMap";
const deviceToolKitInstanceWE100 = new DeviceToolKitWE100("WE100", "M01");
const deviceToolKitInstanceWL200 = new DeviceToolKitWE100("WE100", "WL200");

let currentTimeTimer: any = null; // 当前项目时间定时器
let CountdownTimer: any = null;
let timer: any = null;
let checkVersionTimeout: any = null;
let showTipsTimer: any = null;
let loadingTipsTimer: any = null; // 蓝牙连接提示
let switchModeStatus = "free"; // 用于标记是否在切换模式中, free: 空闲, switching: 切换中
// 设备运行时间校准频率，每多少秒校准一次
const TIME_CALIBRATION_FREQUENCY = 5;

// 模式类型
const WORK_MODE_NAME_ENUM = {
  POWERFULSOOTHING: "powerfulSoothing",
  STABILITY: "Stability",
  BRIGHTEN: "Brighten",
  FIRMSKIN: "FirmSkin",
  MaskCustom: "MaskCustom",
  BrightenStand: "BrightenStand",
  FirmSkinStand: "FirmSkinStand",
  SmallpoxSoothingPro: "SmallpoxSoothingPro",
  SmallpoxSoothing: "SmallpoxSoothing",
  MixNursePro: "MixNursePro",
  MixNurse: "MixNurse",
  ScalpCare: "ScalpCare",
};

// 组合模式：分别对应的是哪几个模式类型
// 黄光590nm
// 红光630nm
// 近红外光830nm

// 模式类型中文名
const WORK_MODE_Chinese_NAME = {
  强效舒缓: "powerfulSoothing",
  维稳修复: "Stability", // 黄光？近红外光?
  均色提亮: "Brighten", // 黄光？近红外光?
  紧致淡纹: "FirmSkin", // 黄光？近红外光?
  自定义: "MaskCustom",
  均色提亮Pro: "BrightenStand",
  紧致淡纹Pro: "FirmSkinStand",
  痘肌舒缓Pro: "SmallpoxSoothingPro",
  痘肌舒缓: "SmallpoxSoothing",
  混合Pro: "MixNursePro",
  混合: "MixNurse",
  头皮护理: "ScalpCare",
};

const MODE_WORKING_ENUM = {
  STANDBY: "standby", // 待命
  WORKING: "working", // 工作
  PAUSE: "pause",
  END: "end",
};

// 倒计时时间
let CountDownTime = {
  powerfulSoothing: 6,
  Stability: 4,
  Brighten: 4,
  FirmSkin: 4,
  MaskCustom: 6,
  BrightenStand: 6,
  FirmSkinStand: 6,
  SmallpoxSoothingPro: 6,
  SmallpoxSoothing: 4,
  MixNursePro: 6,
  MixNurse: 4,
  ScalpCare: 6,
};

let DeviceSyncData = {
  totalWorkingMinutes: 0,
  totalWorkingSeconds: 0,
};
let deviceToolKitInstance = deviceToolKitInstanceWE100; // we100

class IotCarePlan extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "iotCarePlan",
      title: "美容仪名字", // 页面标题
      instrument: "WE200",
      currentDevice: {
        name: "",
        model: "",
      }, // 当前设备

      /** 连接设备 */
      hasVersion: false, // 是否已查询到版本号
      curDeviceInfo: {}, // 当前设备信息
      basicModeList: [], //模式列表
      modelActiveIndex: 0, //模式下标
      sliderProgress: 22,
      isStandStatus: false, // 支架开启状态(支架就是舱体)
      facialMaskConnectStatus: 0, // 面罩连接状态 0未连接 1已连接
      workStatus: "", // 工作状态
      Electricity: 4, // WL200电量
      matrixElectricity: 4, // WE200发箍电量

      workMode: "", //当前模式

      gear: { gear: 1 },
      currentShowDialog: "",
      // countdown: 3, // 倒计时
      step: 1, // 1:选择模式并播放视频, 2:护理中
      isCheckedMaskVersion: false, // 是否检查过固件版本了
      isAskedOta: false, // 询问过用户是否需要OTA
      showVideoPlayBtn: true, // 视频播放按钮
      duration: 0, // 视频总时长
      hadShowBreakTips: false, // 是否展示过支架断开提示
      popupType: "", // enoughTimePopup: 时间达标提示, endPopup: 结束弹窗

      /** 连接设备 End */

      isShowStepTips: false, // 是否显示介绍步骤弹窗
      isConnectionBlutoot: false, // 是否已连接蓝牙
      isShowNurse: false, // 是否开始并显示护理
      isStopNurse: false, // 是否暂停护理
      isEndNurse: false, // 是否结束护理
      errorTips: "", // 错误提示

      // 模式列表
      isSwitchActiveMode: false, // 是否显示弹窗切换模式
      ModeList: [],
      ModeType: "all", // all visor面罩 cabin舱体 yimeish医美
      modeClass: "", // 1面罩 2舱体 3医美
      ActiveModeItem: {}, // 当前选中模式
      SwitchActiveModeItem: {}, // 切换选中模式
      ModeID: "mode_", // 模式KEY
      activeModeID: "", // 当前选中模式ID:用于高亮
      ModeStepIndex: 0, // 当前护理功效步骤：每个步骤时间不定，所以时间另外计算，根据步骤显示
      ModeStepTimeArray: [], // 护理功效时间步骤，用于切换显示GIF
      currentServiceData: {
        // 当前展示的开启暂停GIF: 因为时间判断不方便，所以单独领出来
        startSource: "",
        stopSource: "",
      },
      // 模式组合
      isCombineSuccess: false, // 组合模式是否设置成功

      // 倒计时
      isShowCountdown: false, // 倒计时弹窗
      countdown: 3,

      // 是否结束护理
      isEndCarePlan: false,

      // 最后执行步骤位置
      endPlace: "",
      currentTime: "01:00",
    };
  }

  async onLoad() {
    // 保持屏幕常亮
    Taro.setKeepScreenOn({
      keepScreenOn: true,
    });
  }
  componentDidMount() {
    this.setState({
      videoContext: Taro.createVideoContext("myVideo"),
      standVideoContext: null,
    });
  }

  componentWillUnmount() {}

  componentDidShow() {
    this.initData();
  }

  componentDidHide() {}

  async initData() {
    let objStr = getStorageSync("instrument_detail");
    if (objStr) {
      let info = JSON.parse(objStr);

      this.setState({
        currentDevice: info,
      });

      this.GetModeList(info.id);
      console.log("info");

      // 如果不存在设备模式值，则判断为首次进入，弹窗提示
      let isFirstEntry = getStorageSync("isFirstEntry_" + info.model);
      if (!isFirstEntry) {
        // this.setState({ isShowStepTips: true });
      }
    }

    // 开发者工具
    const platform = Taro.getSystemInfoSync().platform;

    //开发者工具
    if (platform !== "devtools") {
      // 初始化蓝牙
      this.init();
    }

    // 初始化蓝牙
    // this.init();
  }

  async init() {
    // 查询自定义设备指令
    const queryInstructionParams = {
      commandType: "InfoQuery",
      infoQueryType: "customModeInfo",
    };
    let commandBuffer = deviceToolKitInstance.toBleCommand(
      queryInstructionParams as any
    );
    sendCommand({ value: commandBuffer }).then((res) => {
      console.log(
        "查询自定义组合模式指令发送成功 参数为=>",
        queryInstructionParams
      );
    });
    Taro.onBLEConnectionStateChange(this.listener);
    await this.notifyBLECharacteristicValueChange();

    this.handleWorkStatus(false, MODE_WORKING_ENUM.STANDBY);
  }
  listener = (res) => {
    console.log("listener res", res);
    if (res?.connected) return;
    Taro.offBLECharacteristicValueChange((res) => {
      console.log("offBLECharacteristicValueChange", res);
    });
    clearTimeout(loadingTipsTimer);
    // 断开蓝牙关闭倒计时
    this.setState({
      isShowCountdown: false,
    });
    console.log(commandMap.WL200Command, "监听到蓝牙断开, 打开断开提示");
    // 显示蓝牙断开弹窗
    // this.setState({
    //   workStatus: "",
    //   currentShowDialog: "connection_break",
    // });
  };

  GetModeList = async (id) => {
    let params = {
      instrumentId: id,
    };
    let res = await InstrumentInfo.modeInfoList(params);
    if (res.data.code === 200) {
      if (res.data.data.length > 0) {
        this.setState({
          ActiveModeItem: res.data.data[0],
          ModeList: res.data.data,
        });

        this.modeCurrentFun(res.data.data[0]);
      } else {
        this.setState({ ModeList: res.data.data });
      }
    }
  };

  /**
   * 倒计时弹窗
   * param 重置倒计时
   * callback 回调函数
   */
  showCountdownFun(count = 3, callback: any = null) {
    this.setState({
      countdown: count,
    });
    setTimeout(() => {
      clearInterval(CountdownTimer);
      this.setState({
        isShowCountdown: true,
      });
      CountdownTimer = setInterval(() => {
        if (this.state.countdown === 0) {
          clearInterval(CountdownTimer);
          this.setState({
            isShowCountdown: false,
          });
          if (callback) callback();
        } else {
          this.setState({
            countdown: this.state.countdown - 1,
          });
        }
      }, 1000);
    }, 0);
  }

  /** 选中护理模式 */
  modeCurrentFun = async (data) => {
    let currentServiceData = {
      startSource: "",
      stopSource: "",
    };
    if (data.serviceData.length) {
      currentServiceData = data.serviceData[0];
    }

    let currentTime = data.modeTimeStr;
    this.setState({
      ActiveModeItem: data,
      activeModeID: data.id,
      ModeID: "mode_" + data.id,
      currentServiceData,
      ModeStepIndex: 0,
      currentTime,
    });

    setTimeout(() => {
      // 设置时间组合
      if (data.serviceData.length > 0) {
        this.setServiceTimeData();
      }
      // 存在组合模式时，设置组合模式
      if (data.combineData.length > 0) {
        this.setCustomMaskData();
      }
    });
  };
  /** 切换护理模式 */
  switchModeCurrentFun = async (data) => {
    this.setState({
      SwitchActiveModeItem: data,
      activeModeID: data.id,
      ModeID: "mode_" + data.id,
    });
  };
  // 打开模式切换弹窗
  openModeSwitch = () => {
    console.log("openModeSwitch");
    this.setState({
      isSwitchActiveMode: true,
    });
  };
  // 取消并关闭切换护理模式弹窗
  cancelModeSwitchBtn = () => {
    this.setState({
      isSwitchActiveMode: false,
    });
  };
  // 弹窗确定切换护理模式
  confirmModeSwitchBtn = () => {
    let { SwitchActiveModeItem } = this.state;
    let modeArray = ["all", "visor", "cabin", "yimeish"];
    this.setState({
      ModeType: modeArray[SwitchActiveModeItem.modeClass],
    });
    setTimeout(() => {
      this.modeCurrentFun(SwitchActiveModeItem);
      this.cancelModeSwitchBtn();
    }, 100);
  };

  stepNext = () => {
    // //0未定义（全部）  1面罩模式 2舱体模式 3医美术后
    let modeArray = ["all", "visor", "cabin", "yimeish"];
    let modeClass = this.state.ActiveModeItem.modeClass;
    this.setState({
      ModeType: modeArray[modeClass],
      isShowNurse: true,
      isStopNurse: true,
      isStandStatus: this.state.ActiveModeItem.isCabinMode === 1,
      workStatus: "pause",
      step: 2,
    });

    this.handleWorkStatus(false, MODE_WORKING_ENUM.STANDBY);
  };
  /** 开始护理按钮：点击开始，页面进行到下一步 */
  onStartNurse = async () => {
    this.stepNext();
    return;
    let { isConnectionBlutoot } = this.state;
    if (isConnectionBlutoot) {
      this.stepNext();
    } else {
      // todo 提示未连接蓝牙
    }
  };
  /** 切换光照 */
  onSwitchChange = async () => {
    // todo
    let { isStopNurse } = this.state;
    if (isStopNurse) {
      // 开始光照逻辑
      this.onNursingTap();
    } else {
      // 暂停光照逻辑
      this.handleWorkStatus(false, MODE_WORKING_ENUM.PAUSE);
    }
    this.setState({
      isStopNurse: !isStopNurse,
    });
  };

  closeStepTips = (data) => {
    if (data.isLocal) {
      setStorageSync("isFirstEntry_" + this.state.ActiveModeItem.model, true); // 关闭首次进入弹窗
    }
    this.setState({ isShowStepTips: false });
  };

  /** 蓝牙相关 */
  switchBLEMatch = (jsonStatus: any) => {
    switch (jsonStatus.bleCommandType) {
      // 如果设备配对链接发送配对码的时候，设备应答小程序配对码是否正确。
      case "SendMatchCode":
        if (jsonStatus.matchedSuccess) {
          console.log("设备配对成功");
          // log.info(commandMap.WL200Command, "配对成功");
        }
        break;

      // 附属设备状态主动上报，这种指令是主机主动上报某个附属设备断开或者连上了
      case "BleStatusSync":
        switch (jsonStatus.connectMessage?.deviceName) {
          case "WL200":
            console.log(
              "BleStatusSync 附属设备状态主动上报，这种指令是主机主动上报某个附属设备断开或者连上",
              jsonStatus.connectMessage?.connectType == "CONNECTED"
            );
            if (jsonStatus.connectMessage?.connectType == "CONNECTED") {
              // 已连接WL200
              this.setState({ isConnectionBlutoot: true });

              // 附属设备连接成功，如何区分是哪个设备？
              this.setState({
                facialMaskConnectStatus: 1, // 面罩已连接
              });
              deviceToolKitInstance = deviceToolKitInstanceWL200;
              console.log(
                "检查版本isCheckedMaskVersion",
                this.state.isCheckedMaskVersion
              );
              if (!this.state.isCheckedMaskVersion) {
                this.checkVersion();
              }
            } else {
              // WL200连接失败
              // deviceToolKitInstance = deviceToolKitInstanceWE100;
              // // TODO 护理中(step==2)时, 如果断开, 可能需要暂停
              console.log("WL200连接失败或断开");
              this.setState({
                facialMaskConnectStatus: 0,
              });
            }
            break;
          // 是否附属设备是否连接支架
          case "Stand":
            if (jsonStatus.connectMessage?.connectType == "CONNECTED") {
              this.setState({
                isStandStatus: true,
              });
            }
            break;
          default:
            break;
        }
        break;

      //小程序主动问主机，现在链接了哪些附属设备，这时候主机给小程序的回复消息
      case "QueryMatchStatus":
        const isStandDevice =
          jsonStatus?.subDeviceList?.includes("Stand") || false;
        const isConnectedMask =
          jsonStatus?.subDeviceList?.includes("WL200") || false;

        deviceToolKitInstance = isConnectedMask
          ? deviceToolKitInstanceWL200
          : deviceToolKitInstanceWE100;

        console.log("连接and更改成功 deviceToolKitInstance", isConnectedMask);
        if (!this.state.isCheckedMaskVersion && isConnectedMask) {
          this.checkVersion(); // 检查版本
        }
        console.log("支架是否链接", isStandDevice);
        console.log("面罩是否链接", isConnectedMask);
        if (isConnectedMask) {
          this.setState({
            isConnectionBlutoot: true,
            facialMaskConnectStatus: 1,
          });
        }

      // 连上面罩后, 获取仪器记录, 与缓存信息对比,
      // if (
      //   isConnectedMask &&
      //   !this.state.hadGotInstrumentHistoryData
      // ) {
      //   // 如果不延时, 无法获取到仪器状态
      //   const queryDeviceArrayBuffer =
      //     deviceToolKitInstance.toBleCommand(
      //       bleCommandSamples.queryDeviceStatus as any
      //     );
      //   console.log("发送查询设备指令");
      //   sendCommand({
      //     value: queryDeviceArrayBuffer,
      //   });
      //   // 打开ota页面需要关闭
      //   // that.data.getInstrumentHistoryDataTimer = setTimeout(() => {
      //   //   that.getInstrumentHistoryData();
      //   // }, 3000);
      // }
      // this.setData({
      //   isStandStatus: isStandDevice,
      //   facialMaskConnectStatus: `${isConnectedMask ? 1 : 0}`,
      //   // currentTime: this.data.standInfo.currentTime
      // });
    }
  };
  notifyBLECharacteristicValueChange = () => {
    console.log("notifyBLECharacteristicValueChange deviceInfo 参数为=>");
    const bluetoothInfo = this.props.bluetoothInfo;
    notifyBLECharacteristicValueChange({
      deviceId: bluetoothInfo.deviceId,
      servicesuuid: bluetoothInfo.servicesuuid,
      characteristicsuuid1: bluetoothInfo.characteristicsuuid1,
      characteristicsuuid0: bluetoothInfo.characteristicsuuid0,
    }).then((res) => {
      Taro.onBLECharacteristicValueChange((value) => {
        const jsonStatus: any = deviceToolKitInstance.toJsonStatus(value.value);
        console.log(
          "onBLECharacteristicValueChange jsonStatus => ",
          jsonStatus
        );
        // log.info(commandMap.WL200Command, 'onBLECharacteristicValueChange jsonStatus =>', jsonStatus);
        if (!jsonStatus || jsonStatus == null) {
          return;
        }
        // end 和 endWork 都是护理结束, endWork不关机, end 关机, 对小程序而已处理流程都一样
        if (jsonStatus.workStatus && jsonStatus.workStatus == "endWork") {
          jsonStatus.workStatus = "end";
          console.log(jsonStatus.workStatus, "护理结束");
        }

        // 指令类型判断
        switch (jsonStatus?.commandType) {
          case "BleMatch":
            // 蓝牙相关指令
            this.switchBLEMatch(jsonStatus);
            break;

          case "DeviceControl":
            console.log("小程序控制设备，给设备发送指令", jsonStatus);
            //   setTimeout(() => {
            //     console.log("currentTime", this.state.currentTime);
            //   });
            break;
          //设备主动上报给小程序的指令 一般是工作状态改变
          case "DeviceStatusSync":
            console.log(
              "设备主动上报给小程序的指令 一般是工作状态改变",
              jsonStatus
            );
            this.setState({
              Electricity: jsonStatus.battery,
              // fr200Electricity: jsonStatus.battery,
              matrixElectricity: jsonStatus.matrixBattery,
              workStatus: jsonStatus.workStatus,
              workMode: jsonStatus?.workMode,
            });
            // 判断是否在step == 2(护理中)
            if (
              this.state.step == 2 &&
              jsonStatus.workStatus !== MODE_WORKING_ENUM.END
            ) {
              this.updateDeviceSyncData(
                {
                  totalWorkingMinutes: jsonStatus.totalWorkingMinutes,
                  totalWorkingSeconds: jsonStatus.totalWorkingSeconds,
                },
                jsonStatus
              );
            }

            if (
              jsonStatus.workMode === MODE_WORKING_ENUM.WORKING &&
              this.state.step == 2
            ) {
              const { ActiveModeItem } = this.state;
              const item = ActiveModeItem;
              if (jsonStatus.workMode !== item.modeType) {
                clearTimeout(loadingTipsTimer);
                this.setState({
                  isShowCountdown: false,
                });
              }
            }
            break;
          //设备信息查询返回
          case "InfoQuery":
            switch (jsonStatus.infoQueryType) {
              // 自定义模式设置
              case "customModeSet":
                console.log(">>>>>>>>>>>>>>>自定义模式>>>>>>>>>>>>>>>");
                console.log(
                  "InfoQuery customModeSet responseStatus=====>",
                  jsonStatus
                );

                if (jsonStatus.responseStatus == "OK") {
                  console.log("设置成功自定义模式");
                  this.setState({
                    isCombineSuccess: true,
                  });
                }
                break;
              // 自定义模式信息
              case "customModeInfo":
                console.log(
                  "InfoQuery customModeInfo responseStatus=====>",
                  jsonStatus
                );

                break;
              case "versionInfo":
                console.log(
                  "InfoQuery versionInfo responseStatus=====>",
                  jsonStatus
                );
                if (jsonStatus.versionNo) {
                  // 清理计时器
                  if (checkVersionTimeout) clearTimeout(checkVersionTimeout);
                  if (this.state.hasVersion) return;
                  this.setState({
                    hasVersion: true,
                  });
                  this.checkOta(jsonStatus.versionNo);
                }
                break;
              // 当前报告
              case "currentMaskReportInfo":
                console.log("当前面罩报告 currentMaskReportInfo", jsonStatus);
                // if (!this.state.hadCheckReport) {
                //   this.state.hadCheckReport = true;
                //   that.checkInstrumentRecord(jsonStatus);
                // } else {
                //   that.setWL200NursingHistory(jsonStatus);
                // }

                break;
              default:
                break;
            }
            break;
          // default:
          //   break;
        }
      });

      /**
       * 延迟500毫秒获取附属设备状态
       */
      const querySubDeviceArrayBuffer = deviceToolKitInstance.toBleCommand({
        ...bleCommandSamples.querySubDevice,
        queryType: "WL200",
      } as any);
      setTimeout(() => {
        console.log("发送查询指令");
        sendCommand({
          value: querySubDeviceArrayBuffer,
        });
      }, 500);

      /**
       * 延迟500毫秒获取设备电量
       */
      const queryDeviceArrayBuffer = deviceToolKitInstance.toBleCommand(
        bleCommandSamples.queryDeviceStatus as any
      );
      setTimeout(() => {
        console.log("发送查询设备指令");
        sendCommand({
          value: queryDeviceArrayBuffer,
        });
      }, 500);
    });
  };

  // 检查版本
  checkVersion = () => {
    this.sendCheckVersion();
    this.setState({
      isCheckedMaskVersion: true,
    });
    if (checkVersionTimeout) clearTimeout(checkVersionTimeout);
    checkVersionTimeout = setTimeout(() => {
      if (this.state.hasVersion) {
        if (checkVersionTimeout) clearTimeout(checkVersionTimeout);
      } else {
        this.sendCheckVersion();
      }
    }, 600);
  };
  // 检查版本指令
  sendCheckVersion = () => {
    deviceToolKitInstance.setDebug(true);
    // 加定时器查询版本
    const queryVersion = deviceToolKitInstance.toBleCommand({
      commandType: "InfoQuery",
      infoQueryType: "versionInfo",
      otaDeviceType: "WL200",
    });
    sendCommand({
      value: queryVersion,
    });
  };

  checkOta = async (versionNo) => {
    const { iot_versions } = this.state.curDeviceInfo;
    let isNeedToUpdateBl = isNeedToUpdate(versionNo, iot_versions);
    console.log(
      `设备版本号: ${versionNo}`,
      `后台版本号: ${iot_versions}`,
      `是否需要升级: ${isNeedToUpdateBl}`
    );
    if (isNeedToUpdateBl) {
      this.setState({
        isAskedOta: true,
        // currentShowDialog: 'offlineDialog',
      });
      // this.confirmOta();
    }
  };

  //待完善，以后同步设备数据到小程序的事件,在这个事件里判断是否需要更新页面(是否需要触发setData)
  updateDeviceSyncData = (newData, jsonStatus) => {
    DeviceSyncData = {
      ...DeviceSyncData,
      ...newData,
    };
    if (newData.hasOwnProperty("totalWorkingSeconds")) {
      this.renderDeviceStatus.renderWorkTime(jsonStatus);
    }
  };

  // 页面同步护理剩余时间
  renderDeviceStatus = {
    renderWorkTime: (jsonStatus) => {
      const { totalWorkingMinutes, totalWorkingSeconds } = DeviceSyncData;
      let { ActiveModeItem, currentTime } = this.state;
      const totalTime = totalWorkingMinutes * 60 + totalWorkingSeconds;
      console.log("仪器上报的已经运行的总秒数", totalTime);
      console.log("时间校准频率，默认5秒一次", TIME_CALIBRATION_FREQUENCY);
      //对比仪器上报运行的总秒数  和小程序页面运行的已经运行的总秒数，如果不一致就进行校准
      const currentScene = ActiveModeItem; // 获取当前的场景
      let sceneTime = minSecToS(currentScene.modeTimeStr); // 场景时间

      console.log("场景时间 sceneTime", sceneTime);
      console.log("当前显示时间 currentTime", currentTime);
      console.log("设备运行时间 totalTime", totalTime);
      console.log(" this.state.step", this.state.step);
      console.log("sceneTime > totalTime", sceneTime > totalTime);

      // 更新界面倒计时
      this.resetTimer();

      if (
        sceneTime > totalTime &&
        this.state.step == 2 &&
        this.state.facialMaskConnectStatus == 1
      ) {
        // 界面倒计时同步设备时间
        const t = sceneTime - totalTime; // 场景时间 - 已运行时间 = 剩余时间
        this.setState({
          currentTime: s_to_ms(t),
        });
      } else {
        this.setState({
          currentTime: "00:00",
          endPlace: "report",
        });
        this.judgementWorkStatus(
          MODE_WORKING_ENUM.END,
          jsonStatus.workMode,
          jsonStatus
        );
      }
    },
  };

  // 仪器开始倒计时
  setLoadingTips(time) {
    this.setState({
      countdown: time,
    });
    if (time >= 0) {
      loadingTipsTimer = setTimeout(() => {
        this.setLoadingTips(--time);
      }, 1000);
    } else {
      // 停止倒计时
      // that.data.startSettingCountDown = false;
      this.setState({
        isShowCountdown: false,
      });
    }
  }

  /**
   * 设备上报不同状态
   * params 工作状态 工作模式 响应状态
   */
  judgementWorkStatus(nWorkStatus, nWorkMode, jsonStatus) {
    const {
      workStatus,
      step,
      isStandStatus,
      workMode,
      ActiveModeItem,
      ModeList,
    } = this.state;
    const opts: any = {};
    // ActiveModeItem
    let nowModeItem;
    if (nWorkMode) {
      nowModeItem = ModeList.find((item) => {
        return item.modeType === nWorkMode;
      });
    }
    opts.workStatus = nWorkStatus;
    const statusF = {
      sleep: () => {
        this.setState({
          isShowCountdown: false,
        });
      },
      standby: () => {
        this.setState({
          isShowCountdown: false,
        });
        if (nowModeItem?.isStandMode && step == 2) {
          opts.currentTime = nowModeItem.modeTime;
        } else if (!nowModeItem?.isStandMode && step == 2) {
          // fix: 启动非支架模式倒计时时，连上支架，仪器的状态变为standby
          opts.step = 1;
        }
      },
      setting: () => {
        // that.data.hadShowBreakTips = false;
        this.setState({
          hadShowBreakTips: false,
        });
        if (step != 2 && !ActiveModeItem.isCabinMode) {
          opts.step = 2;
          this.setState({
            title: "正在护理",
            isStopNurse: false,
          });
        } else if (step != 2 && ActiveModeItem.isCabinMode) {
          opts.step = 2;
          // this.setState({
          //   title: "正在护理",
          // });
          this.setState({
            title: "正在护理",
            isStopNurse: false,
          });
        }
        if (nowModeItem) {
          opts.currentTime = nowModeItem.modeTime;
        }
        // startSettingCountDown 用于标记打开了倒计时loading
        if (!this.state.isShowCountdown) {
          this.setState({
            isShowCountdown: true,
          });
          this.setLoadingTips(CountDownTime[workMode] || 6);
        }
      },
      working: () => {
        if (this.state.facialMaskConnectStatus != 1) {
          opts.workStatus = MODE_WORKING_ENUM.STANDBY;
          opts.step = 1;
        } else if (step != 2) {
          opts.step = 2;
          this.setState({
            title: "正在护理",
            isStopNurse: false,
          });
        }

        this.setState({
          isShowCountdown: false,
          hadShowBreakTips: false,
        });
      },
      pause: () => {
        clearInterval(currentTimeTimer);
        this.setState({
          isShowCountdown: false,
        });
        if (ActiveModeItem.isCabinMode) {
          // this.onPauseTap();
          this.setState({
            title: "暂停护理",
            isStopNurse: true,
          });
        }
      },
      end: () => {
        // 仪器返回护理结束, 支架模式不需要了
        // if (modeItem.isStandMode) {
        //     this.onPauseTap();
        // }
        // 已进入了报告阶段, 防止重复进入, 主要防止在手动点击结束护理接收到仪器消息
        console.log("END 护理结束");
        clearInterval(currentTimeTimer);

        this.endnursing(true);
      },
    };
    statusF[nWorkStatus] && statusF[nWorkStatus]();
    if (Object.keys(opts).length) {
      this.setState(opts);
    }
  }

  /**
   * 保存护理报告
   * 1.是否跳转 2.数据
   * */
  saveNurseReport = async (isJump = true, from) => {
    this.endNurseFun();
  };

  /**
   * 结束护理
   * param isAuto 是否仪器自动结束
   */
  endnursing = (isAuto) => {
    if (isAuto == true) {
      // 仪器自动上报完成, 直接上报并跳转报告页
      clearInterval(currentTimeTimer);
      const isEnough = this.checkTime();
      if (isEnough && !this.state.endPlace) {
        this.setState({
          endPlace: "report",
        });
        this.saveNurseReport(true, "endnursing");
      }
    } else {
      // 手动点击结束, 弹出弹窗, 看看是否需要结束
      this.onEndPlan();
    }
  };

  isInTimeScope(start, end, targetMinute, targetSecond) {
    const startTime = dayjs().set("minute", start).set("second", 0);
    const endTime = dayjs().set("minute", end).set("second", 0);
    const targetTime = dayjs()
      .set("minute", targetMinute)
      .set("second", targetSecond); // 要判断的时间，这里使用当前时间作为示例
    let inTime = false;
    if (
      (targetTime.isAfter(startTime) && targetTime.isBefore(endTime)) ||
      targetTime.isSame(startTime) ||
      targetTime.isSame(endTime)
    ) {
      inTime = true;
    }
    return inTime;
  }

  // 重置计时器
  resetTimer = () => {
    // 切换模式后, 需要重新设置计时器, 以防进行中的计时器
    currentTimeTimer && clearInterval(currentTimeTimer);
    currentTimeTimer = setInterval(() => {
      let {
        workStatus,
        step,
        facialMaskConnectStatus,
        currentTime,
        ModeStepTimeArray,
        ModeStepIndex,
        ActiveModeItem,
      } = this.state;
      if (
        workStatus == MODE_WORKING_ENUM.WORKING &&
        step == 2 &&
        facialMaskConnectStatus == 1
      ) {
        let totalSeconds = minSecToS(ActiveModeItem.modeTimeStr);
        let currentSeconds = minSecToS(currentTime);
        let checkTime = totalSeconds - currentSeconds;
        console.log("设备已运行多少秒", checkTime);
        console.log("ModeStepTimeArray", ModeStepTimeArray);
        if (currentSeconds >= 1) {
          this.setState({
            currentTime: s_to_ms(--currentSeconds),
          });

          let length = ModeStepTimeArray.length;
          if (length) {
            // 模式多个步骤节点切换

            // 已运行时间达到下一节点时，切换
            if (checkTime > ModeStepTimeArray[ModeStepIndex]) {
              // 已运行时间达到下一节点，步骤切换时更新
              if (ModeStepIndex < length) {
                let index = ModeStepIndex + 1; // 提前步骤+1
                let currentServiceData = {
                  startSource: "",
                  stopSource: "",
                };
                let serviceLength = ActiveModeItem.serviceData.length;
                if (serviceLength > index) {
                  currentServiceData = ActiveModeItem.serviceData[index];
                }

                console.log("********************");
                console.log("********************");
                console.log(
                  "仅在时间达到下一步，步骤切换时更新currentServiceData",
                  currentServiceData
                );

                this.setState({
                  ModeStepIndex: index,
                  currentServiceData,
                });
              }
            }
          }
        } else {
          clearInterval(currentTimeTimer);
          this.setState({
            currentTime: "00:00",
            endPlace: "report",
            ModeStepIndex: 0,
          });
          this.saveNurseReport(true, "setTimer"); // 保存护理计划，并且结束
        }
      }
    }, 1000);
  };

  // 检测并控制工作状态
  handleWorkStatus = (isBtnClick: boolean, workStatus) => {
    const { facialMaskConnectStatus, isStandStatus, ActiveModeItem } =
      this.state;
    let newWorkStatus =
      workStatus ||
      (this.state.workStatus == MODE_WORKING_ENUM.WORKING
        ? "pause"
        : "working");
    if (isBtnClick && newWorkStatus == "working") {
      // 舱体模式
      if (ActiveModeItem.isCabinMode === 1 && !isStandStatus) {
        this.showTips(
          `检测到舱体未连接成功，请确认面罩开机后与舱体连接，并接通舱体电源`
        );
        return;
      }
      // 非舱体模式
      if (!ActiveModeItem.isCabinMode && facialMaskConnectStatus != 1) {
        console.log("facialMaskConnectStatus", facialMaskConnectStatus);
        this.showTips("检测到面罩未连接成功，请确认面罩开机并佩戴");
        return;
      }
    }

    // // 工作状态，开始组合模式
    // if (
    //   this.state.ActiveModeItem.combineData.length &&
    //   this.state.workStatus == MODE_WORKING_ENUM.WORKING
    // ) {
    //   this.startCombinationMode();
    // }

    const sendParams = {
      ...deviceCommandSamples.pause,
      workMode: ActiveModeItem.modeType, // 使用模式
      // workMode: "MaskCustom",
      workStatus: newWorkStatus,
    };
    const pauseArrayBuffer = deviceToolKitInstance.toBleCommand(
      sendParams as any
    );
    sendCommand({
      value: pauseArrayBuffer,
    }).then(() => {
      this.setState({
        workStatus: newWorkStatus,
      });
      this.resetTimer();
      console.info(
        `handleWorkStatus 发送${newWorkStatus}指令成功 参数为 =>`,
        sendParams
      );
    });
  };

  /**
   * 点击开始护理
   */
  onNursingTap() {
    // 防止多次点击
    if (this.state.hadClickStart) return;
    this.setState({
      hadClickStart: true,
    });
    setTimeout(() => {
      this.setState({
        hadClickStart: false,
      });
    }, 500);
    const {
      ActiveModeItem,
      workStatus,
      isStandStatus,
      facialMaskConnectStatus,
      customModeData,
    } = this.state;
    const modelActiveItem = ActiveModeItem;
    // log.info(
    //   commandMap.WL200Command,
    //   "点击开始护理按钮",
    //   `当前模式: ${modelActiveIndex}`,
    //   `当前面罩状态:${facialMaskConnectStatus}`,
    //   `当前仪器模式:${workStatus}`
    // );
    console.info(
      commandMap.WL200Command,
      "点击开始护理按钮",
      `当前模式: ${ActiveModeItem.modeType}`,
      `当前面罩状态:${facialMaskConnectStatus}`,
      `当前仪器模式:${workStatus}`
    );
    console.log(modelActiveItem);
    console.log("isStandStatus:" + isStandStatus);
    console.log(
      workStatus !== MODE_WORKING_ENUM.WORKING &&
        workStatus !== MODE_WORKING_ENUM.STANDBY &&
        workStatus !== MODE_WORKING_ENUM.PAUSE
    );

    if (facialMaskConnectStatus != 1) {
      console.log("facialMaskConnectStatus 开始处", facialMaskConnectStatus);
      this.showTips("检测到面罩未连接成功，请确认面罩开机并佩戴");
      return;
    }
    // 如果是强效舒缓,需要判断是否连接支架
    if (modelActiveItem.isStandMode && !isStandStatus) {
      this.showTips(
        `检测到舱体未连接成功，请确认面罩开机后与舱体连接，并接通舱体电源`
      );
      return;
    } else if (!modelActiveItem.isStandMode && isStandStatus) {
      this.showTips(`检测到面罩仍和舱体连接中，请分离后切换`);
      return;
    }
    if (
      ActiveModeItem.modeType === "MaskCustom" &&
      !this.state.isCombineSuccess
    ) {
      this.showTips(`${modelActiveItem.modeName}模式设置失败，请联系小助手`);
      return;
    }
    // 开始执行护理
    this.handleWorkStatus(true, MODE_WORKING_ENUM.WORKING);
    this.showCountdownFun(3, () => {}); // 倒计时弹窗
  }

  // 结束护理？
  endNurseFun() {
    this.handleWorkStatus(false, "end");
    this.PostNursingLogClock();
    // setTimeout(() => {
    //   //TODO  IOS关闭蓝牙太快导致关机指令没发出去，暂时这么解决
    //   const isEnough = this.checkTime();
    //   if (!isEnough) {
    //     Taro.showModal({
    //       title: "提示",
    //       content: "护理时间不足，请重新连接护理",
    //       showCancel: false,
    //       success: (res) => {
    //         if (!this.state.endPlace || this.state.endPlace !== "report") {
    //           // back();
    //           console.log("back");
    //         }
    //         // this.state.innerAudioContext.destroy();
    //         Taro.closeBluetoothAdapter();
    //       },
    //     });
    //   } else {
    //     if (!this.state.endPlace || this.state.endPlace !== "report") {
    //       // back();
    //       console.log("back");
    //     }
    //     // this.state.innerAudioContext.destroy();
    //     Taro.closeBluetoothAdapter();
    //   }
    // }, 500);
  }

  // 检查时间是否达标
  checkTime() {
    const { currentDevice, ActiveModeItem } = this.state;
    const currentScene = ActiveModeItem;
    let sceneTime = minSecToS(currentScene.modeTimeStr);
    const timeRemaining = sceneTime - minSecToS(this.state.currentTime); // 当前模式已运行时间

    let nursingTimeStr = currentDevice?.nursingTimeStr;
    let nursingTime = nursingTimeStr ? minSecToS(nursingTimeStr) : 60; // 设备生成护理记录至少需要运行时间

    if (timeRemaining >= nursingTime) {
      return true;
    } else {
      return false;
    }
  }

  // 删除WL200护理历史
  rmWL200NursingHistory(WL200NursingHistory, hard = false) {}

  //蓝牙断开连接处理
  bluetoothDisconnectProcessing() {
    clearInterval(timer);
    Taro.offBLEConnectionStateChange(this.listener); // 需传入与监听时同一个的函数对象
    Taro.offBLECharacteristicValueChange((res) => {
      console.log("offBLECharacteristicValueChange", res);
    });
    if (!this.state.isToOTA) {
      Taro.closeBluetoothAdapter();
    }
  }

  // 获取护理时间组合
  getServiceTimeData() {
    const { ActiveModeItem } = this.state;
    let serviceData = ActiveModeItem.serviceData.map((item) => {
      // let totalWorkingMinutes = parseInt(item.modeTimeStr.split(":")[0]); // 仅分钟数
      // let totalWorkingSeconds = parseInt(item.modeTimeStr.split(":")[1]); // 仅秒数
      let totalWorkingMinutes = 1; // 仅分钟数
      let totalWorkingSeconds = 0; // 仅秒数
      return {
        totalWorkingMinutes,
        totalWorkingSeconds,
      };
    });
    console.log(
      "组合时间ServiceTimeData",
      serviceData,
      ActiveModeItem.serviceData
    );
    return serviceData;
  }
  // 设置护理时间组合
  setServiceTimeData() {
    let ServiceTimeData = this.getServiceTimeData();

    // 组合时间
    let ModeStepTimeArray: any = [];
    ServiceTimeData.reduce((old, cur) => {
      let curTime = cur.totalWorkingMinutes * 60 + cur.totalWorkingSeconds;
      let newTotalWorkingMinutes = cur.totalWorkingMinutes;
      let newTotalWorkingSeconds = cur.totalWorkingSeconds;
      if (old) {
        newTotalWorkingMinutes += old.totalWorkingMinutes;
        newTotalWorkingSeconds += old.totalWorkingSeconds;

        let oldTime = old.totalWorkingMinutes * 60 + old.totalWorkingSeconds;
        let value = oldTime + curTime;
        console.log("value", value);
        ModeStepTimeArray.push(value);
        return {
          totalWorkingMinutes: newTotalWorkingMinutes,
          totalWorkingSeconds: newTotalWorkingSeconds,
        };
      }
      console.log("curTime", curTime);
      ModeStepTimeArray.push(curTime);
      return {
        totalWorkingMinutes: newTotalWorkingMinutes,
        totalWorkingSeconds: newTotalWorkingSeconds,
      };
    }, null);
    this.setState({
      ModeStepTimeArray: ModeStepTimeArray,
      ModeStepIndex: 0, // 每次切换组合模式，重置组合步骤
    });
    console.log("组合时间ModeStepTimeArray", ModeStepTimeArray);
  }
  /* 组合模式 */
  // 获取自定义组合模式原数组
  getOriginModesArray = () => {
    const { ModeList, ActiveModeItem } = this.state;
    const combineIds = ActiveModeItem.combineData.map(
      (item) => item.combineModeId
    );
    let modesArray = ModeList.filter((item) => combineIds.includes(item.id));
    return modesArray;
  };
  // 获取自定义组合模式数组
  getCustomModesArray = () => {
    const { ModeList, ActiveModeItem } = this.state;
    const combineIds = ActiveModeItem.combineData.map(
      (item) => item.combineModeId
    );
    let modesArray = ModeList.filter((item) =>
      combineIds.includes(item.id)
    ).map((item) => {
      let totalWorkingMinutes = parseInt(item.modeTimeStr.split(":")[0]); // 仅分钟数
      let totalWorkingSeconds = parseInt(item.modeTimeStr.split(":")[1]); // 仅秒数
      return {
        workMode: item.modeType,
        totalWorkingMinutes,
        totalWorkingSeconds,
      };
    });
    return modesArray;
  };
  setCustomMaskData() {
    console.log("================");
    console.log("setCustomMaskData");
    console.log("================");

    // modesArray 发送组合模式数组指令到设备存储
    let modesArray = this.getCustomModesArray();
    console.log("组合模式modesArray", modesArray);

    let customModeSetCommand = {
      commandType: "InfoQuery",
      infoQueryType: "customModeSet",
      modesArray,
    };
    let commandBuffer = deviceToolKitInstance.toBleCommand(
      customModeSetCommand as any
    );
    sendCommand({
      value: commandBuffer,
    }).then((res) => {
      console.info("发送切换组合模式指令成功", res);
    });
  }
  // 发送启动组合模式指令
  startCombinationMode() {
    const jsonCommand = {
      commandType: "DeviceControl",
      workStatus: "working",
      workMode: "MaskCustom",
    };
    let commandBuffer = deviceToolKitInstance.toBleCommand(jsonCommand as any);
    sendCommand({
      value: commandBuffer,
    }).then(() => {
      console.info("发送启动组合模式指令成功  参数为 =>", jsonCommand);
    });
  }

  // 护理的错误提示
  showTips(ctx) {
    if (!ctx) return;
    if (showTipsTimer) clearTimeout(showTipsTimer);
    this.setState({
      errorTips: ctx,
    });
    showTipsTimer = setTimeout(() => {
      this.setState({
        errorTips: "",
      });
    }, 2000);
  }

  /** 结束护理弹窗 */
  onEndPlan = async () => {
    this.setState({
      isEndCarePlan: true,
    });
  };
  confirmEndBtn = () => {
    this.endNurseFun();
    this.cancelEndBtn();
  };
  cancelEndBtn = () => {
    this.setState({
      isEndCarePlan: false,
    });
  };
  /** 弹窗 END*/

  /** 护理记录 */
  // apiClock
  PostNursingLogClock = async () => {
    let { currentDevice, ActiveModeItem } = this.state;
    let params = {
      instrumentId: currentDevice.id,
      instrumentName: currentDevice.name,
      modeId: ActiveModeItem.id,
      modeName: ActiveModeItem.modeName,
      nursingTime: ActiveModeItem.modeTime,
    };
    let res: any = await InstrumentInfo.apiNursingLog.addLog(params);
    console.log("PostNursingLogClock", res);
  };
  /** 护理记录 End */

  render() {
    let {
      name,
      title,
      isShowStepTips,
      isConnectionBlutoot,
      isShowNurse,
      isStopNurse,
      ModeList,
      ModeType,
      currentServiceData,
      ActiveModeItem,
      SwitchActiveModeItem,
      isSwitchActiveMode,
      ModeID,
      activeModeID,
      isShowCountdown,
      countdown,
      ModeStepIndex,
      Electricity,
      matrixElectricity,
      errorTips,
      isEndCarePlan,
      currentTime,
      facialMaskConnectStatus,
    } = this.state;
    return (
      <Block>
        <Navbar titleSlot={title} isBack={true} />

        <View catchMove>
          <PopupCountdown isShow={isShowCountdown} countdown={countdown} />
          <PopupConfirm
            isLarge={true}
            isShow={isEndCarePlan}
            isClose={true}
            title="提示"
            content="是否结束护理"
            textAlgin="center"
            cancelButtonText="取消"
            confirmButtonText="确定"
            close={this.cancelEndBtn}
            confirm={this.confirmEndBtn}
          />
          <PopupConfirm
            isLarge={true}
            isShow={isSwitchActiveMode}
            isClose={true}
            title="护理模式切换"
            content={
              <ModeListView
                ModeID={ModeID}
                activeModeID={activeModeID}
                isPop={true}
                isShowNurse={isShowNurse}
                ModeList={ModeList}
                ModeType={ModeType}
                ActiveModeItem={SwitchActiveModeItem}
                onEmit={this.switchModeCurrentFun}
                onEmitShowAll={this.openModeSwitch}
              />
            }
            textAlgin="center"
            cancelButtonText="取消"
            confirmButtonText="确定"
            close={this.cancelModeSwitchBtn}
            confirm={this.confirmModeSwitchBtn}
          />

          {ActiveModeItem.openSourceData && (
            <PopupStepTips
              isShow={isShowStepTips}
              isLarge={true}
              title={"" + "准备中"}
              confirmButtonText="开始护理"
              data={ActiveModeItem.openSourceData}
              close={this.closeStepTips}
            />
          )}
        </View>

        <View>
          <View className="iot-main">
            <View className="banner-box">
              <View>
                {!isShowNurse && (
                  <Video
                    className="video-or-image"
                    src={ActiveModeItem.modeVideo}
                  />
                )}

                {isShowNurse && (
                  <Block>
                    {isStopNurse ? (
                      <Image
                        className="video-or-image"
                        src={currentServiceData.stopSource}
                      />
                    ) : (
                      <Image
                        className="video-or-image"
                        src={currentServiceData.startSource}
                      />
                    )}
                  </Block>
                )}

                {errorTips && (
                  <Block>
                    <View className="msg-tips">
                      <Image
                        className="msg-tips-img"
                        src={require("../../img/tips.png")}
                      />
                      <View className="msg-tips-content">{errorTips}</View>
                    </View>
                  </Block>
                )}
              </View>

              <View className="iot-device">
                <View className="item">
                  <Text className="device-time">
                    护理时间：
                    <Text className="time">{currentTime}</Text>
                  </Text>
                </View>
                <View className="line" />
                <ElectricityView
                  Electricity={Electricity}
                  matrixElectricity={matrixElectricity}
                  facialMaskConnectStatus={facialMaskConnectStatus}
                />
              </View>
            </View>

            {ModeList.length > 0 && (
              <ModeListView
                isPop={false}
                isShowNurse={isShowNurse}
                ModeList={ModeList}
                ModeType={ModeType}
                ModeID={ModeID}
                activeModeID={activeModeID}
                ActiveModeItem={ActiveModeItem}
                onEmit={this.modeCurrentFun}
                onEmitShowAll={this.openModeSwitch}
              />
            )}

            <ModeContent
              isShowNurse={isShowNurse}
              ActiveModeItem={ActiveModeItem}
            />
          </View>

          <Footer
            isConnectionBlutoot={isConnectionBlutoot}
            isShowNurse={isShowNurse}
            isStopNurse={isStopNurse}
            onEmitStartNurse={this.onStartNurse}
            onEmitSwitchChange={this.onSwitchChange}
            onEmitEndPlan={this.onEndPlan}
          />
        </View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  bluetoothInfo: state.deviceInfo.bluetoothInfo,
});
const mapDispatchToProps = (dispatch) => ({
  // userRefresh(data) {
  //   dispatch(userRefresh(data));
  // },
});
export default connect(mapStateToProps, mapDispatchToProps)(IotCarePlan);
