import classnames from "classnames";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import { Component } from "react";
import {
  Block,
  View,
  Text,
  Image,
  Swiper,
  SwiperItem,
} from "@tarojs/components";

/*** redux ***/
import { connect } from "react-redux";
import { userRefresh, tokenRefresh } from "@/store/features/userInfo";
import { setIndexFlag } from "@/store/features/globalStore";
/*** redux end ***/

/** 自定义组件 **/
import AtCalendar from "@/components/calendar";
import PopupPrivacy from "@/components/popup/popup-privacy";
import PopupBinding from "@/components/popup/popup-binding";
// import PopupPrivacyTest from "../../components/popup/popup-privacy-test";

import PopupSiteSwiper from "@/components/popup/popup-site-swiper";
import PopupAlert from "@/components/popup/popup-alert";
import type CustomTabBar from "@/custom-tab-bar";
import Navbar from "@/components/navbar/navbar";

import ConnectionBluetoot from "@/components/bluetoot/connection";
/** 自定义组件 **/

import {
  RefreshWxUserInfo,
  GetNoReadMessageNum,
  GetSitePopupList,
  GetSiteCarousel,
  GetSiteAddTag,
  InstrumentInfo,
  WCUserLogin,
} from "../../utils/Interface";

// css引入
import "taro-ui/rn/style/components/calendar.scss";
import "./index.less";
import {
  go,
  goJump,
  msg,
  getStorageSync,
  setStorageSync,
  showModal,
} from "@/utils/traoAPI";
import commandMap from "@/utils/commandMap";

import InstrumentTypeEnum from "@/components/bluetoot/instrumentTypeEnum";
import OtaDeviceTypeEnum from "@/components/bluetoot/OtaDeviceTypeEnum";

const log = require("@/utils/log");

class Index extends Component<any, any> {
  // pageCtx = Taro.getCurrentInstance().page;
  $instance = Taro.getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      isRegisterBoolean: false, // 是否已登录
      isShowPrivacyPopup: false,
      isShowSiteSwiper: false,
      isNotRegister: false, // 是否未注册
      isDev: false, // 正在开发提示
      sitePopupList: [], // 站点管理列表
      userinfo: {
        mobile: Taro.getStorageSync("mobile"),
      },

      list: [],
      params: "",
      messageCount: Taro.getStorageSync("messageCount") || 0,
      offlineDialogType: 1, //1离线弹窗 2升级弹窗
      offlineDialogForce: 0, //0可选是否升级  1强制升级
      versioninfo: {}, //仪器版本号,
      info: {}, // 护理推荐点击参与活动的信息
      weekinfo: undefined,
      // 日历
      currentDate: dayjs().format("YYYY-MM-DD"),
      calendarComplete: [
        dayjs().subtract(1, "day").format("YYYY-MM-DD"),
        dayjs().subtract(3, "day").format("YYYY-MM-DD"),
      ],
      calendarInComplete: [
        dayjs().add(1, "day").format("YYYY-MM-DD"),
        dayjs().add(8, "day").format("YYYY-MM-DD"),
      ],
      // 横幅轮播
      bannerList: [],
      bannerCurrent: 0,

      /** 绑定仪器 */
      isVisibleBinding: false, // 绑定弹窗
      isBindingError: false, // 绑定失败
      isBeforeBinding: false, // 已绑定弹窗
      instrumentList: [], // 仪器列表
      instrumentInfo: {
        // 扫码获得的序列号仪器
        bindingStatus: 0, // 0已绑定，1未绑定，2已解绑
        createBy: null,
        createTime: "2024-01-19 17:46:10",
        exportFields: [],
        id: 4,
        instrumentId: 82,
        instrumentIdArray: null,
        instrumentName: "研发测试FR380",
        instrumentSerialIdList: [],
        queryInstrumentIds: null,
        remark: null,
        serial: "", // 设备序列号
        source: "导入",
        status: 0, // 0正常 1停用
        updateBy: null,
        updateTime: null,
        validStatus: 1, // 1有效，0无效
      },
      /** 绑定仪器 End */

      /** 已绑定仪器 */
      instrument_detail: {},
      /* 已绑定仪器 END */

      /** 蓝牙相关 */
      isConnectShow: false,
      connectInstrument: {},
      yiqiinfo: {},
      /* END  */
    };
  }

  async onLoad() {
    console.log(1123131233);

    // 仅非扫码进入页面时，校验跳转欢迎页
    if (!this.$instance.router?.params?.q) {
      const isFirst = Taro.getStorageSync("isWelcome");
      if (!isFirst) {
        go("/pages/initiate/initiate");
      }
    }
    if (Taro.getStorageSync("skip")) {
      this.setState({ showEquipment: true })
      Taro.removeStorageSync('skip');
    }
  }

  componentDidMount() {

  }

  componentWillUnmount() { }

  componentDidShow() {
    const tabbar = Taro.getTabBar<CustomTabBar>(this.$instance.page);
    tabbar?.setSelected(0);

    this.showInit();
  }

  componentDidHide() { }

  showInit() {
    // 判断是否登录
    let mobile = Taro.getStorageSync("mobile");
    if (mobile) {
      this.setState({ isRegisterBoolean: true });
    }
    // 非扫码进入小程序，需判断是否跳转欢迎页；扫码进入小程序，先缓存序列号，再检测隐私弹窗
    let url = this.$instance.router?.params?.q || "";
    if (!url) {
      // 非扫码进入
      Taro.setStorageSync("isScan", false);
      const isFirst = Taro.getStorageSync("isWelcome");
      if (isFirst) {
        this.checkShowPrivacyPopup();
      }
    } else {
      // 扫码进入
      Taro.setStorageSync("isScan", true);
      if (url) {
        let _url = decodeURIComponent(url);
        if (_url.indexOf("?")) {
          let ids = _url.split("?");
          if (ids.length > 1) {
            let serial = ids[1];
            Taro.setStorageSync("serial", serial);
            if (!Taro.getStorageSync("mobile")) {
              go("/pages/register/register");
            }
          }
        }
      }
      this.checkShowPrivacyPopup();
    }
  }

  // 检测是否弹出隐私协议
  checkShowPrivacyPopup() {
    Taro.getPrivacySetting({
      success: (res) => {
        // console.log("检测是否弹出隐私协议", res); // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          this.setState({ isShowPrivacyPopup: true });
        } else {
          // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
          // this.initData();
          this.isSancQrcodeEnter();
        }
      },
      fail: () => { },
      complete: () => {
        // 授权完成运行页面初始化
      },
    });
  }

  // 页面初始化
  async initData() {
    let token = getStorageSync("token");
    if (!token) {
      // 如果token过期，先登录，登录完成后自动初始化
      await this.WCUserLogin();
    } else {
      // token没过期，直接请求数据
      this.initPageData();
    }
  }

  async initPageData() {
    const mobile = Taro.getStorageSync("mobile");
    this.GetSiteCarousel();

    if (mobile) {
      this.GetNoReadMessageNum(); // 查询是否有消息
      await this.bindingInstrumentList(); // 获取已绑定设备
      await this.getInstrumentInfoBySerial(); // 扫码序列号查询：注册后才调用，因为扫码未注册直接跳转注册页

      if (!this.props.isShowIndexFlag) {
        this.GetSitePopupList();
        // 全局内存缓存，仅初次进入首页运行
        this.props.setIndexFlag(true);
        // 小程序切到后台，则清除弹窗缓存
        Taro.onAppHide((res) => {
          console.log("小程序进入后台：", res);
          this.props.setIndexFlag(false);
        });
      }
    }
  }

  // 刷新用户信息
  RefreshWxUserInfo = async () => {
    let res = await RefreshWxUserInfo();
    if (res.data.code === 200) {
      this.props.userRefresh(res.data.data);
    }
  };

  // 获取消息数量
  GetNoReadMessageNum = async () => {
    let res = await GetNoReadMessageNum();
    if (res.data.code === 200) {
      Taro.setStorageSync("messageCount", res.data.data);
      this.setState({ messagecount: res.data.data });
    }
  };

  // 获取站点管理-弹窗列表 1-首页 2-发现模块 3-活动模块
  GetSitePopupList = async () => {
    let res = await GetSitePopupList(1);
    if (res.data.code === 200) {
      if (res.data.data) {
        if (res.data.data.length) {
          this.setState({
            sitePopupList: res.data.data,
            isShowSiteSwiper: true,
          });
        }
      }
    }
  };

  // 获取站点管理-广告轮播列表
  GetSiteCarousel = async () => {
    let res = await GetSiteCarousel();
    if (res.data.code === 200) {
      if (res.data.data) {
        this.setState({ bannerList: res.data.data });
      }
    }
  };

  GetSiteAddTag = async (id) => {
    let res = await GetSiteAddTag(id);
    if (res.data.code === 200) {
      console.log("点击自动上报，不需要逻辑处理");
    }
  };

  goRegister() {
    go("/pages/register/register");
  }

  // 新增设备
  addNewDevice = () => {
    if (this.isRegister("addNewDevice")) {
      // todo
      go("/pages/instrument/instrument");
    }
  };

  // 是否已注册
  isRegister(type = "") {
    if (type === "addNewDevice") {
      Taro.setStorageSync("isInstrumentJump", "true"); // 判断是否点击新增设备按钮，用于信息完善页判断跳转逻辑
    } else {
      Taro.setStorageSync("isInstrumentJump", "false"); // 重置
    }
    if (!this.state.isRegisterBoolean) {
      this.alertRegister();
      return false;
    }
    return true;
  }

  showPrivacy = () => {
    this.setState({ isShowPrivacyPopup: true });
  };

  closePrivacy = () => {
    this.setState({ isShowPrivacyPopup: false });
    this.initData();
  };

  closeAlert = () => {
    this.setState({ isNotRegister: false });
  };

  public alertRegister = () => {
    this.setState({ isNotRegister: true }); // 打开弹窗
  };

  onTimeChange = (value) => {
    console.log("onTimeChange", value);
    this.setState({ currentDate: value });
  };

  // 护理记录
  toNursingRecords = () => {
    go("/pages/recording/recording");
  };

  gourl = (e) => {
    const { url } = e.currentTarget.dataset;
    if (this.isRegister()) {
      go(url);
    }
  };

  closeDev = () => {
    this.setState({ isDev: false });
  };

  closeSiteSwiper = () => {
    this.setState({ isShowSiteSwiper: false });
  };

  bannerSwiperchange() { }

  gobanner(item) {
    // 跳转类型：0无跳转、1跳转内部链接、3跳转外部链接、4跳转小程序、5导向视频号、6导向视频号直播间',
    /**
     *  `link`  ： '跳转链接（跳转外部链接、跳转内部链接）',
        `link_params` ： '跳转链接参数（跳转内部链接）',
        `redirect_appid` ： '外链小程序appid（跳转小程序）',
        `redirect_url` ： '外链小程序url（跳转小程序）',
        `video_no` ： '视频号（导向视频号、导向视频号直播间）',
        `feed_id` ： '视频号feedId（导向视频号）',
    */
    let { id } = item;
    this.GetSiteAddTag(id);

    goJump(item);
  }

  /* 仪器与是否扫码进入逻辑 */
  // 获取已绑定仪器列表
  bindingInstrumentList = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { data: res } = await InstrumentInfo.bindingInstrumentList();
    Taro.hideLoading();
    if (res.code === 200) {
      this.setState({ instrumentList: res.data });
    } else {
      // 仪器列表失败todo
    }
  };
  // 是否扫码进入小程序
  isSancQrcodeEnter = async () => {
    let instance = Taro.getCurrentInstance();
    let q = instance.router?.params?.q;
    if (q) {
      // 扫码进入强制重新登录
      this.WCUserLogin();
    } else {
      this.initData();
    }
  };
  async WCUserLogin() {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    const { code } = await Taro.login();
    const { data } = await WCUserLogin({ code });
    Taro.hideLoading();

    if (data.code === 200) {
      Taro.setStorageSync("isWelcome", true);
      Taro.setStorageSync("mobile", data.data.mobile);
      this.props.tokenRefresh(data.data);

      setTimeout(() => {
        this.initPageData();
      }, 300);
    } else {
      msg("请求失败,尝试重新请求");
      this.WCUserLogin();
    }
  }
  closeBinding = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isVisibleBinding: false });
  };
  confirmBinding = () => {
    let { isExchangeBinding } = this.state;

    if (!isExchangeBinding) {
      // 绑定仪器
      this.bindingInstrument();
    } else {
      // 换绑仪器
      this.exchangeBinding();
    }
  };
  // 根据扫码的序列号获取仪器信息
  getInstrumentInfoBySerial = async () => {
    let url = this.$instance.router?.params?.q || "";
    let isScan = Taro.getStorageSync("isScan"); // 判断是否扫码进入
    let serial = Taro.getStorageSync("serial"); // 扫码可能跳转注册页，所以先缓存
    if (url || isScan) {
      let { data } = await InstrumentInfo.getInstrumentInfoBySerial({
        serial: serial,
      });
      if (data.code === 200) {
        let instrumentInfo = data.data;
        // 更新扫码进入仪器信息
        this.setState({ instrumentInfo: instrumentInfo });

        // 1有效 0无效
        if (instrumentInfo.validStatus === 0) {
          this.setState({ isBindingError: true });
          return;
        }
        // 0已绑定 1未绑定  2已解绑
        if (instrumentInfo.bindingStatus === 0) {
          // 选择仪器有误
          this.setState({
            isBeforeBinding: true,
          });
          return;
        } else if (
          instrumentInfo.bindingStatus === 1 ||
          instrumentInfo.bindingStatus === 2
        ) {
          setTimeout(() => {
            this.isBindingSerial();
          }, 100);
        }
      } else {
        // 获取失败和绑定失败一个弹窗
        this.setState({ isBindingError: true });
      }
    }
  };

  /** 查询是否可以绑定 */
  isBindingSerial = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let res = await InstrumentInfo.isBindingSerial({
      serial: instrumentInfo.serial,
    });
    console.log("isBindingSerial", res);
    if (res.data.code === 201) {
      // 绑定
      this.setState({ isExchangeBinding: false, isVisibleBinding: true });
    } else if (res.data.code === 202) {
      // 换绑
      this.setState({ isExchangeBinding: true, isVisibleBinding: true });
    }
    Taro.hideLoading();
  };
  /** 调用接口绑定仪器 */
  bindingInstrument = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.binding({
      serial: instrumentInfo.serial,
    });
    Taro.hideLoading();
    this.closeBinding();
    if (data.code === 200) {
      msg("绑定成功");
      setTimeout(() => {
        go("/pages/instrument/intro?id=" + instrumentInfo.id);
      }, 2000);
      return;
    } else if (data.code === 202) {
      // 换绑操作
      this.setState({ isExchangeBinding: true, isVisibleBinding: true });
    } else if (data.code === 201) {
      // 跳转联系客服
      this.setState({ isBindingError: true });
    } else {
      this.setState({ isBindingError: true });
    }
  };

  exchangeBinding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.exchangeBinding({
      serial: instrumentInfo.serial,
    });
    console.log("exchangeBinding", data);
    Taro.hideLoading();
    this.closeBinding();
    if (data.code === 200) {
    } else {
      this.closeBinding();
      this.setState({ isBindingError: true });
    }
  };
  // 仪器绑定失败弹窗
  onBindErrorClose = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isBindingError: false });
  };
  onBindErrorConfirm = () => {
    this.onBindErrorClose();
    go("/pages/consultant/consultant");
  };
  onBeforeBindClose = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isBeforeBinding: false });
  };
  onBeforeBindConfirm = () => {
    this.setState({ isBeforeBinding: false });
  };

  // 跳转仪器介绍页
  goNursing = (item) => {
    console.log("goNursing", item);
    setStorageSync("instrument_detail", JSON.stringify(item));
    this.setState({ connectInstrument: item });
    setTimeout(() => this.bindBlockLeft());
  };
  /* 扫码进入逻辑 */

  /** 蓝牙逻辑 */
  bindBlockLeft() {
    if (!this.state.isRegisterBoolean) {
      //未注册授权
      this.alertRegister();
      return false;
    }
    if (this.state.connectInstrument.type === 1) {
      //非IOT
      setTimeout(() => {
        go("/pages/instrumentClickinUpload/index");
      }, 10);
    } else {
      Taro.getSystemInfo({
        success: (res) => {
          console.log("getSystemInfo", res);
          let { locationEnabled, locationAuthorized, bluetoothEnabled } = res;
          if (!locationEnabled || !locationAuthorized) {
            showModal({
              t2: "您的手机定位授权未开启，请前往手机设置，打开定位访问授权",
              btn2text: "查看指引",
            }).then(() => {
              go("/pages/connection_help/connection_help?type=location");
            });
          } else if (!bluetoothEnabled) {
            showModal({
              t2: "您的手机蓝牙授权未开启，请前往手机设置，打开蓝牙访问授权",
              btn2text: "查看指引",
            }).then(() => {
              go("/pages/connection_help/connection_help?type=bluetoot");
            });
          } else {
            // 打开连接弹窗
            this.connectionOpen();
          }
        },
      });
    }
  }

  /**
   * WE100,WL200配对完成回调
   */
  pairingChange = (e) => {
    console.log("===epairingChange===》", e);
    go("/pages/iotCarePlan/iotCarePlan"); // 画页面直接跳转

    this.connectionClose();
  };

  async goIot() {
    go("/pages/iotCarePlan/iotCarePlan"); // 画页面直接跳转
    // return;
  }
  onUnloginConfirm() {
    this.setState({ showEquipment: false })
  }
  onUnloginClose() {
    this.setState({ showEquipment: false })
  }
  //连接完成时数据的回调
  offlineChange = async (e) => {
    console.log("offlineChange", e);
    // log.info(
    //   commandMap.versionInfoHome,
    //   `offlineChange::e::${JSON.stringify(e)}`
    // );
    //offlineDataList 离线数据
    //versioninfo 版本号
    let { offlineDataList, versionInfo } = e.detail;
    this.setState({
      versionInfo,
    });
    let offlinelist: any = [];
    offlineDataList.map((item, index) => {
      let obj: any = {
        clock_day: "",
        status: 3,
        second: 120,
        screne_id: "",
        screne_name: "离线打卡",
        model_face_ward: 0,
        model_face_use: 0,
        model_face_type: "",
        model_eye_ward: 0,
        model_eye_use: 0,
        model_eye_type: "",
        instrument_id: this.state.connectInstrument.id,
      };

      //判断日期是否正常，如果不正常不处理 --- 脸部
      if (
        item.faceyear > 0 &&
        item.faceyear <= 99 &&
        item.facemonth >= 1 &&
        item.facemonth <= 12 &&
        item.faceday >= 1 &&
        item.faceday <= 31
      ) {
        if (
          item.facehour > 0 ||
          (item.faceminutes > 0 && item.faceminutes < 60) ||
          (item.faceseconds > 0 && item.faceseconds < 60)
        ) {
          //脸部离线记录有值
          obj.model_face_use =
            Number(item.facehour) * 60 * 60 +
            Number(item.faceminutes) * 60 +
            Number(item.faceseconds);
          obj.model_face_ward = item.faceposition1;
          obj.clock_day = `20${String(item.faceyear).padStart(2, "0")}-${String(
            item.facemonth
          ).padStart(2, "0")}-${String(item.faceday).padStart(2, "0")}`;
        }
      }
      //判断日期是否正常，如果不正常不处理 --- 眼部
      if (
        item.eyeyear > 0 &&
        item.eyeyear <= 99 &&
        item.eyemonth >= 1 &&
        item.eyemonth <= 12 &&
        item.eyeday >= 1 &&
        item.eyeday <= 31
      ) {
        if (
          item.eyehour > 0 ||
          (item.eyeminutes > 0 && item.eyeminutes < 60) ||
          (item.eyeseconds > 0 && item.eyeseconds < 60)
        ) {
          //眼部离线记录有值
          obj.model_eye_use =
            Number(item.eyehour) * 60 * 60 +
            Number(item.eyeminutes) * 60 +
            Number(item.eyeseconds);
          obj.model_eye_ward = item.eyeposition1;
          obj.clock_day = `20${String(item.eyeyear).padStart(2, "0")}-${String(
            item.eyemonth
          ).padStart(2, "0")}-${String(item.eyeday).padStart(2, "0")}`;
        }
      }

      obj.second = obj.model_face_use + obj.model_eye_use;

      if (
        item.faceyear > 0 &&
        item.faceyear <= 99 &&
        (item.facemonth == 1 || item.facemonth <= 12) &&
        (item.faceday == 1 || item.faceday <= 31)
      ) {
        let dayTime = new Date(`${obj.clock_day.replace(/-/g, "/")}`).getTime(); //离线记录的日期
        let now = new Date(
          `${new Date().getFullYear()}/${String(
            new Date().getMonth() + 1
          ).padStart(2, "0")}/${String(new Date().getDate()).padStart(2, "0")}`
        ).getTime(); //当前日期
        /**
         * 过滤7天前的离线记录
         *
         */
        if (dayTime <= now && dayTime >= now - 24 * 60 * 60 * 1000 * 6) {
          offlinelist.push(obj);
        }
      }
    });
    console.log(offlinelist);
  };

  connectionOpen = async () => {
    this.setState({ isConnectShow: true });
  };
  connectionClose = async () => {
    this.setState({ isConnectShow: false });
  };
  connectionConfirm = async () => {
    this.connectionClose();
  };

  /*蓝牙 END*/
  render() {
    let {
      calendarComplete,
      calendarInComplete,
      currentDate,
      messagecount,
      sitePopupList,
      isShowPrivacyPopup,
      isNotRegister,
      isShowSiteSwiper,
      isDev,

      bannerList,
      bannerCurrent,
      // 绑定弹窗
      isVisibleBinding,
      isBindingError,
      isBeforeBinding,
      isRegisterBoolean,
      isExchangeBinding,
      instrumentInfo,
      instrumentList,
      showEquipment,

      // 蓝牙连接
      isConnectShow,
      connectInstrument,
    } = this.state;

    return (
      <Block>
        <View catchMove>
          <PopupAlert
            isShow={isNotRegister}
            isClose
            title='提示'
            content='暂未授权注册，请点击注册'
            confirmButtonText='确定'
            textAlgin='center'
            type='1'
            close={this.closeAlert}
            confirm={this.closeAlert}
          />
          <PopupAlert
            isShow={isDev}
            title='提示'
            content='页面正在开发中'
            confirmButtonText='确定'
            textAlgin='center'
            close={this.closeDev}
            confirm={this.closeDev}
          />
          <PopupPrivacy
            isShow={isShowPrivacyPopup}
            closePrivacy={this.closePrivacy}
          />

          <PopupBinding
            type={instrumentInfo.bindingStatus}
            isShow={isVisibleBinding}
            isRegisterBoolean={isRegisterBoolean}
            isExchangeBinding={isExchangeBinding}
            data={instrumentInfo}
            close={this.closeBinding}
            confirm={this.confirmBinding}
          />
          <PopupAlert
            isShow={isBindingError}
            title='提示'
            content={
              <Block>
                <View>序列号信息仍在更新，请联系微信小助理</View>
                <View>协助您绑定仪器</View>
              </Block>
            }
            confirmButtonText='知道了'
            textAlgin='center'
            isClose={false}
            close={this.onBindErrorClose}
            confirm={this.onBindErrorConfirm}
          ></PopupAlert>
          <PopupAlert
            isShow={isBeforeBinding}
            title='提示'
            content='您选择的仪器有误，请重新确认选择'
            confirmButtonText='知道了'
            textAlgin='center'
            isClose={false}
            close={this.onBeforeBindClose}
            confirm={this.onBeforeBindConfirm}
          ></PopupAlert>

          <PopupAlert
            isShow={showEquipment}
            title='提示'
            content={
              <Block>
                <View className='mb10'>仪器：小紫单美容仪</View>
                <View className='mb10'>序列号：uniquie14231</View>
                <View className='mb10'>您需要完成注册登录才能进行一起绑定</View>
              </Block>
            }
            confirmButtonText='知道了'
            textAlgin='center'
            isClose={false}
            close={this.onUnloginClose.bind(this)}
            confirm={this.onUnloginConfirm.bind(this)}
          ></PopupAlert>

          {/* <PopupPrivacyTest
          closePrivacy={this.closePrivacy.bind(this)}
          initData={this.initData.bind(this)}
        ></PopupPrivacyTest> */}

          <PopupSiteSwiper
            isShow={isShowSiteSwiper}
            siteData={sitePopupList}
            size='middle'
            confirmButtonText='确定'
            textAlgin='center'
            close={this.closeSiteSwiper}
            confirm={this.closeSiteSwiper}
          />
        </View>

        {isConnectShow && (
          <ConnectionBluetoot
            yiqiInfo={connectInstrument}
            close={this.connectionClose}
            confirm={this.connectionConfirm}
            offlineChange={this.offlineChange}
            pairingChange={this.pairingChange}
          />
        )}
        {/* <ConnectionBluetoot /> */}

        <Navbar
          leftSlot={
            <Block>
              <View
                className='message'
                onClick={this.gourl}
                data-url='/pages/message/message'
              >
                <Image
                  className='message-img'
                  src={require("../../img/index/message.png")}
                  mode='aspectFill'
                />
                {messagecount ? <View className='tip' /> : ""}
              </View>
            </Block>
          }
        />
        <View className='index'>
          <View className='date-title' onClick={this.toNursingRecords}>
            <Text className='text'>护理记录</Text>
            <Image
              src={require("../../img/index/right.png")}
              style='width: 20rpx;height: 20rpx;'
            />
          </View>
          <View className='bg-while'>
            <AtCalendar
              hideArrow
              isSwiper={false}
              currentDate={currentDate}
              complete={calendarComplete}
              incomplete={calendarInComplete}
              maxDate={Date.now()}
              onTimeChange={this.onTimeChange}
            />
          </View>
        </View>
        <View className='infobox5'>
          {instrumentList.length > 0 && (
            <Block>
              <View className='nurse_plan_box flex  aitems sb'>
                <View className='title'>前往护理</View>
                <View
                  className='txt_box flex jcenter aitems'
                  data-url='/pages/instrument/instrument'
                  onClick={this.gourl}
                >
                  <Image
                    className='right_icon'
                    src={require("../../img/black-add.png")}
                    mode='aspectFill'
                  />
                  <View className='txt'>添加新设备</View>
                </View>
              </View>

              <View style='overflow-x: auto;'>
                <View className='device_list flex'>
                  {instrumentList.map((item, index) => {
                    if (item.status === 0) {
                      return (
                        <View
                          key={"instrumentList" + index}
                          className='device_item'
                          onClick={this.goNursing.bind(this, item)}
                        >
                          <Image
                            className='banner_img'
                            src={item.banner}
                            mode='aspectFill'
                          />
                          <View className='device_name ellipsis1'>
                            {item.name}
                          </View>
                        </View>
                      );
                    }
                  })}
                </View>
              </View>
            </Block>
          )}
          {instrumentList.length === 0 && (
            <Block>
              <View className='nurse_plan_box flex aitems sb'>
                <View className='title'>前往护理</View>
              </View>
              <View className='add_device flex jcenter aitems bg-while'>
                <View className='add_device_btn'>
                  <View className='txt_box flex jcenter aitems'>
                    <View
                      className='at-icon at-icon-add'
                      style='color: #fff;font-size: 30rpx;'
                    ></View>
                    <View className='txt' onClick={this.addNewDevice}>
                      添加新设备
                    </View>
                  </View>
                </View>
                <View className='tips'>您暂时还没有绑定任何设备</View>
              </View>
            </Block>
          )}
        </View>

        <View style='margin: 20px'>
          <View onClick={this.goIot}>假按钮跳转蓝牙调试设备页</View>
        </View>

        <View className='infobox3'>
          <Swiper
            autoplay
            onAnimationFinish={this.bannerSwiperchange.bind(this)}
            current={bannerCurrent}
          >
            {bannerList.map((item, index) => {
              return (
                <SwiperItem
                  key={"banner_" + index}
                  onClick={this.gobanner.bind(this, item)}
                >
                  <Image style='width:100%;height:100%' src={item.fileUrl} />
                </SwiperItem>
              );
            })}
          </Swiper>
        </View>
        <View style='height:200rpx'></View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  background: state.navigation.background,
  mobile: state.userInfo.mobile,
  isShowIndexFlag: state.globalStore.isShowIndexFlag,
});
const mapDispatchToProps = (dispatch) => ({
  userRefresh(data) {
    dispatch(userRefresh(data));
  },
  tokenRefresh(data) {
    dispatch(tokenRefresh(data));
  },
  setIndexFlag(data) {
    dispatch(setIndexFlag(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Index);
