import classnames from "classnames";
setSerial;
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import { Component } from "react";
import {
  Block,
  View,
  Text,
  Image,
  Swiper,
  SwiperItem,
  RichText,
} from "@tarojs/components";
import { Popup } from "@antmjs/vantui";
/*** redux ***/
import { connect } from "react-redux";
import { userRefresh, tokenRefresh } from "@/store/features/userInfo";
import { setIndexFlag } from "@/store/features/globalStore";
import {
  setInstrument,
  setSerial,
  setInstrumentName,
} from "@/store/features/instrument";
/*** 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 PopupConfirm from "@/components/popup/popup-confirm";
import type CustomTabBar from "@/custom-tab-bar";
import Navbar from "@/components/navbar/navbar";

import ConnectionBluetoot from "@/components/bluetoot/connection";
import UpdateIotWL200 from "@/components/bluetoot/update-wl200/index";
/** 自定义组件 **/

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";

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

class Index extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      isDisabledClickAddDevice: false, // 是否禁止点击添加设备
      isCommonError: false, // 是否显示通用错误提示
      commonErrorText: [], // 通用错误提示

      showEquipment: false, // 扫码绑定设备弹窗
      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, // 绑定失败
      isBeforeBindingError: false, // 绑定前校验错误弹窗
      BeforeBindingErrorText: "", // 绑定前校验错误文本
      isBindingError203: false, // 绑定失败弹窗:已被别人绑定

      instrumentList: [], // 仪器列表
      ViewAddInstrument: true, // 查看是否添加有仪器
      unbindingInstrumentList: [], // 未绑定仪器列表
      instrumentInfo: {
        // 扫码获得的序列号仪器
        bindingStatus: 0, // 0已绑定，1未绑定，2已解绑
        createBy: null,
        createTime: "2024-01-19 17:46:10",
        exportFields: [],
        id: 0,
        instrumentId: 0,
        instrumentIdArray: null,
        instrumentName: "",
        instrumentSerialIdList: [],
        queryInstrumentIds: null,
        remark: null,
        serial: "", // 设备序列号
        source: "导入",
        status: 0, // 0正常 1停用
        updateBy: null,
        updateTime: null,
        validStatus: 1, // 1有效，0无效
      },
      /** 绑定仪器 End */

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

      /** 蓝牙相关 */
      isConnectShow: false,
      connectInstrument: {}, // 当前连接设备
      /* END  */

      // 设备升级弹窗
      isShowUpdateVersionTip: false, // 升级提示
      isShowVersionUpgrading: false, // 升级中
      isShowVersionUpgradFinish: false, // 升级完成：升级内容公告
      versionUpgradFinishNodes: "", // 公告内容

      // 设备是否重连弹窗
      isShowReConnectDeviceRecordWL200: false,
    };
  }

  async onLoad(options) {
    console.log("onLoad options", options);
    if (options) {
      if (options?.q) {
        Taro.setStorageSync("isScan", true);
        let url = options.q;
        let _url = decodeURIComponent(url);
        if (_url.indexOf("?")) {
          let ids = _url.split("?");
          if (ids.length > 1) {
            let serial = ids[1];
            Taro.setStorageSync("serial", serial);
          }
        }
        console.log("Taro.getCurrentInstance()", Taro.getCurrentInstance());
        Taro.reLaunch({ url: "/pages/index/index" }); // 链接扫码进入，需要清空router，重置地址栏参数防止bug
      }
    }
    // 仅非扫码进入页面时，校验跳转欢迎页
    let $instance: any = Taro.getCurrentInstance();
    console.log("$instance", $instance);
    if (!$instance.router?.params?.q) {
      const isFirst = Taro.getStorageSync("isWelcome");
      if (!isFirst) {
        go("/pages/initiate/initiate");
      }
    }
  }

  componentDidMount() {}

  componentWillUnmount() {
    // 页面卸载监听
    Taro.offAppHide((res) => {
      console.log("页面卸载监听 offAppHide");
    });
  }

  componentDidShow() {
    const handleAsyncLogic = async () => {
      // tabbar icon切换
      let $instance: any = Taro.getCurrentInstance();
      const tabbar = Taro.getTabBar<CustomTabBar>($instance.page);
      tabbar?.setSelected(0);
      // 扫码仪器数据同步
      this.setState({
        instrumentInfo: this.props.storeInstrument,
      });

      // 判断是否跳过了注册
      if (Taro.getStorageSync("skipRegister")) {
        await this.EquipmentNo(); // 扫码序列号查询：注册后才调用，因为扫码未注册直接跳转注册页
        this.setState({ showEquipment: true });
        Taro.removeStorageSync("skipRegister");
      } else {
        // 已注册且非跳过,正常执行逻辑
        setTimeout(() => {
          this.showInit();
        });
      }
    };
    handleAsyncLogic();
  }

  componentDidHide() {
    this.closeUpgradeBox();
  }

  /**
   * 关闭升级弹窗
   * 如果升级中，则在熄屏时，强制关闭
   * */
  closeUpgradeBox() {
    if (this.state.isShowVersionUpgrading) {
      this.wl200UpgradeErrorFun();
      Taro.closeBluetoothAdapter();
      setStorageSync("isDisconnectUpdate", true); // 已断开更新
    }
  }

  showInit = async () => {
    // 判断是否登录
    let mobile = Taro.getStorageSync("mobile");
    if (mobile) {
      this.setState({ isRegisterBoolean: true });
    }

    // 直接检查隐私弹窗
    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.isSancQrcodeEnter();
        }
      },
      fail: () => {},
      complete: () => {
        // 授权完成运行页面初始化
      },
    });
  }

  // 页面初始化
  initData = async () => {
    let token = getStorageSync("token");

    if (!token) {
      // 如果token过期，先登录，登录完成后自动初始化
      await this.WCUserLogin();
    } else {
      // token没过期，直接请求数据
      this.initPageData();
    }
  };
  // 查看设备序号与仪器
  EquipmentNo = async () => {
    let serial = Taro.getStorageSync("serial"); // 扫码可能跳转注册页，所以先缓存
    let { data } = await InstrumentInfo.getInstrumentInfoBySerial({
      serial: serial,
    });

    if (data.code === 200) {
      let instrumentInfo = data.data;
      // 更新扫码进入仪器信息
      this.setState({ instrumentInfo: instrumentInfo });
      this.props.setInstrument(instrumentInfo);

      // 1有效 0无效
      // if (instrumentInfo.validStatus === 0) {
      //   this.setState({ isBindingError: true });
      //   return;
      // }
      // // 0已绑定 1未绑定  2已解绑
      // if (instrumentInfo.bindingStatus === 0) {
      //   setTimeout(() => {
      //     this.isBindingSerial();
      //   }, 100);
      //   let isBind = this.state.instrumentList.find(
      //     (item) => item.id === instrumentInfo.id
      //   );
      //   if (isBind) {
      //     this.setState({
      //       isBeforeBindingError: true,
      //       BeforeBindingErrorText: "序列号已绑定",
      //     });
      //   } else {
      //     this.setState({
      //       isBeforeBindingError: true,
      //       BeforeBindingErrorText: "序列号已被其他用户绑定",
      //     });
      //   }

      //   return;
      // } else if (
      //   instrumentInfo.bindingStatus === 1 ||
      //   instrumentInfo.bindingStatus === 2
      // ) {
      //   // 判断是否已绑定同名仪器，如果已绑定，判断序列号是否一致
      //   // 如果自己已绑定，判断扫码序列号和已绑定序列号是否一致，如果一致：忽略
      //   // 如果自己已绑定，判断扫码序列号和已绑定序列号是否一致，如果不一致：提示换绑
      //   // 以上逻辑交给后端处理，直接查询是否绑定或换绑
      //   setTimeout(() => {
      //     this.isBindingSerial();
      //   }, 100);
      // }
    }
    // this.removeScanFun();
  };
  initPageData = async () => {
    const mobile = Taro.getStorageSync("mobile");
    const isToken = getStorageSync("token");
    if (!isToken) {
      // 防止逻辑出错没有token
      await this.onlyLogin();
    }
    // 如果是扫码且已有token则跳转
    let serial = Taro.getStorageSync("serial");
    if (serial) {
      if (!mobile) {
        // 如果未注册绑定手机号，就去注册
        setTimeout(() => {
          go("/pages/register/register");
        }, 300);
        return;
      }
    }

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

      console.log("this.props.isShowIndexFlag", this.props.isShowIndexFlag);
      if (!this.props.isShowIndexFlag) {
        this.initDeviceNursingHistory();
        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) => {
    go("/recoding/pages/moisture_test_report/moisture_test_report");
    let res = await GetSiteAddTag(id);
    if (res.data.code === 200) {
      console.log("点击自动上报，不需要逻辑处理");
    }
  };

  goRegister() {
    go("/pages/register/register");
  }
  // 查看所有设备是否绑定完
  Alldevice = () => {
    console.log(this.state.isDisabledClickAddDevic, "查看");
  };
  // 新增设备
  addNewDevice = () => {
    if (this.isRegister("addNewDevice")) {
      if (this.state.isDisabledClickAddDevice) {
        msg("您已绑定所有设备");
        return;
      }
      go("/instrument/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.isSancQrcodeEnter(); // 关闭隐私弹窗后,需要判断是否扫码进入
  };

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

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

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

  // 护理记录
  toNursingRecords = () => {
    let { ViewAddInstrument } = this.state;
    // go(`/pages/recording/recording?param1=${param1Value}`);
    go(`/recoding/pages/recording/recording?param=${ViewAddInstrument}`);
  };

  gourl = async (e) => {
    console.log("添加新设备", e);

    const { url } = e.currentTarget.dataset;
    if (this.isRegister()) {
      if (url === "/instrument/pages/instrument/instrument") {
        let { data } = await InstrumentInfo.unbindingInstrumentInfoList();
        console.log(data, "查看未绑定设备");
        if (data.data.length === 0) {
          this.setState({
            show: true,
          });
          setTimeout(() => {
            this.setState({ show: false });
          }, 1000); // 2秒后将 show 变量置为 false
        } else {
          go(url);
        }
      } else {
        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);
  }

  /* 仪器与是否扫码进入逻辑 */

  isVideo = (str) => {
    if (str.includes(".mp4")) {
      return true;
    }
    return false;
  };
  // 未绑定列表
  unbindingInstrumentInfoList = async () => {
    let { data } = await InstrumentInfo.unbindingInstrumentInfoList();
    if (data.code === 200) {
      if (data.data.length === 0) {
        this.setState({
          isDisabledClickAddDevice: true,
        });
      } else {
        this.setState({
          unbindingInstrumentList: data.data,
        });
      }
    }
  };
  // 获取已绑定仪器列表
  bindingInstrumentList = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { data: res } = await InstrumentInfo.bindingInstrumentList();
    console.log(res, "查看绑定的设备");

    // Taro.hideLoading();
    if (res.code === 200) {
      if (res.data.length === 0) {
        this.setState({ ViewAddInstrument: false });
      }
      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();
    }
  };
  WCUserLogin = async () => {
    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("请求失败,尝试重新请求");
      setTimeout(() => {
        this.WCUserLogin();
      }, 2000);
    }
  };

  // 只登陆，不做其他操作
  onlyLogin = async () => {
    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);
    } else {
      msg("请求失败,尝试重新请求");
    }
  };

  closeBinding = () => {
    this.setState({ isVisibleBinding: false });
  };
  confirmBinding = () => {
    let { isExchangeBinding } = this.state;

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

    if (url || isScan) {
      let { data } = await InstrumentInfo.getInstrumentInfoBySerial({
        serial: serial,
      });
      console.log(data, "查看赋值");

      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) {
          let isBind = this.state.instrumentList.find(
            (item) => item.id === instrumentInfo.instrumentId
          );
          if (isBind) {
            msg("序列号已绑定");
          } else {
            this.setState({
              isBeforeBindingError: true,
              BeforeBindingErrorText: "序列号已被其他用户绑定",
            });
          }
          return;
        } else if (
          instrumentInfo.bindingStatus === 1 ||
          instrumentInfo.bindingStatus === 2
        ) {
          // 判断是否已绑定同名仪器，如果已绑定，判断序列号是否一致
          // 如果自己已绑定，判断扫码序列号和已绑定序列号是否一致，如果一致：忽略
          // 如果自己已绑定，判断扫码序列号和已绑定序列号是否一致，如果不一致：提示换绑
          // 以上逻辑交给后端处理，直接查询是否绑定或换绑
          setTimeout(() => {
            this.isBindingSerial();
          }, 100);
        }
      } else {
        // 获取失败和绑定失败一个弹窗
        this.setState({ isBindingError: true });
      }

      this.removeScanFun();
    }
  };

  /** 查询是否可以绑定 */
  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, unbindingInstrumentList } = this.state;
    let { data } = await InstrumentInfo.binding({
      serial: instrumentInfo.serial,
    });
    console.log("bindingInstrument", data);
    Taro.hideLoading();
    this.closeBinding();
    this.removeScanFun();
    if (data.code === 200) {
      msg("绑定成功");

      let obj = unbindingInstrumentList.find(
        (item) => item.id === instrumentInfo.instrumentId
      );
      if (obj) {
        setStorageSync("instrument_detail", obj);
      }

      setTimeout(() => {
        // 绑定成功后，先查询设备介绍页，有数据则跳转，没数据则刷新已绑定数据
        this.getInstrumentIntroInfo(instrumentInfo.instrumentId);
      }, 500);
      return;
    } else if (data.code === 204) {
      this.setState({
        isBeforeBindingError: true,
        BeforeBindingErrorText: "您选择的仪器有误，请重新选择确认",
      });
    } else if (data.code === 203) {
      this.setState({ isBindingError203: true });
    } else if (data.code === 202) {
      // 换绑操作
      this.setState({ isExchangeBinding: true, isVisibleBinding: true });
    } else {
      this.setState({ isBindingError: true });
    }
  };

  /** 获取设备介绍页信息:绑定判断是否存在介绍信息，如果存在则跳转，不存在则回到首页 */
  getInstrumentIntroInfo = async (id) => {
    let res = await InstrumentInfo.instructionInfo({
      instrumentId: id,
    });
    console.log("res", res);
    if (res.data.code === 200) {
      if (res.data.data.length > 0) {
        go("/instrument/pages/instrument/intro?customBack=true&id=" + id);
      } else {
        this.bindingInstrumentList();
      }
    }
  };

  // 换绑仪器
  exchangeBinding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.exchangeBinding({
      serial: instrumentInfo.serial,
    });
    Taro.hideLoading();
    this.closeBinding();
    if (data.code === 200) {
      msg("换绑成功");
      setTimeout(() => {
        let obj = this.state.unbindingInstrumentList.find(
          (item) => item.id === instrumentInfo.instrumentId
        );
        if (obj) {
          setStorageSync("instrument_detail", obj);
        }
        this.getInstrumentIntroInfo(instrumentInfo.instrumentId);
      }, 500);
    }
  };
  // 仪器绑定失败弹窗
  // 绑定失败
  onBindErrorClose = () => {
    this.setState({ isBindingError: false });
    this.removeScanFun();
  };
  onBindErrorConfirm = () => {
    this.onBindErrorClose();
    go("/pages/consultant/consultant?customBack=true");
  };
  // 已被别人绑定
  onBindErrorClose203 = () => {
    this.setState({ isBindingError203: false });
  };
  onBindErrorConfirm203 = () => {
    this.onBindErrorClose203();
    go("/pages/consultant/consultant");
  };
  // 绑定后弹窗
  onBeforeBindClose = () => {
    this.setState({ isBeforeBindingError: false });
    this.removeScanFun();
  };
  onBeforeBindConfirm = () => {
    this.setState({ isBeforeBindingError: false });
    this.removeScanFun();
  };
  /**删除扫码缓存*/
  removeScanFun = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
  };

  // 跳转仪器介绍页
  goNursing = (item) => {
    console.log("connectInstrument", item);
    // 仅开发者工具调试使用
    const platform = Taro.getSystemInfoSync().platform;
    // setStorageSync("instrument_detail", item);
    // this.setState({ connectInstrument: item });
    // setTimeout(() => this.goIot());
    // return;
    if (platform === "devtools") {
      setStorageSync("instrument_detail", item);
      this.setState({ connectInstrument: item });
      if (item.type === 1) {
        //非IOT
        setTimeout(() => {
          go("/instrument/pages/instrumentClickinUpload/index");
        }, 10);
      } else {
        setTimeout(() => this.goIot());
      }
      return;
    }

    // 移动端真正逻辑
    if (item.status === 0) {
      setStorageSync("instrument_detail", item);
      this.setState({ connectInstrument: item });
      setTimeout(() => this.bindBlockLeft());
    } else {
      this.openCommonError([
        "该仪器暂时无法进行在线护理，",
        "请联系微信小助理",
      ]);
    }
  };
  /* 扫码进入逻辑 */

  /** 蓝牙逻辑 */
  bindBlockLeft() {
    if (!this.state.isRegisterBoolean) {
      //未注册授权
      this.alertRegister();
      return false;
    }
    if (this.state.connectInstrument.type === 1) {
      //非IOT
      setTimeout(() => {
        go("/instrument/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);
    if (this.state.connectInstrument.model === "FR200") {
      go("/moduleIOT/pages/iotCarePlan/FR200"); // 画页面直接跳转
    } else {
      go("/moduleIOT/pages/iotCarePlan/WL200"); // 画页面直接跳转
    }
    this.connectionClose();
  };

  async goIot() {
    if (this.state.connectInstrument.model === "FR200") {
      go("/moduleIOT/pages/iotCarePlan/FR200"); // 画页面直接跳转
    } else {
      go("/moduleIOT/pages/iotCarePlan/WL200"); // 画页面直接跳转
    }
    // return;
  }

  //连接完成时数据的回调
  offlineChange = async (e) => {
    console.log("offlineChange", e);
    this.pairingChange("offlineChange");
  };

  connectionOpen = async () => {
    this.setState({ isConnectShow: true });
  };
  connectionClose = async () => {
    this.setState({ isConnectShow: false });
  };
  connectionConfirm = async () => {
    this.connectionClose();
  };
  /*蓝牙 END*/

  /** 设备iot固件版本升级 */
  // 是否更新弹窗
  upgradeFun = () => {
    this.setState({ isShowUpdateVersionTip: true, isConnectShow: false });
  };
  cancelUpdateVersionTip = () => {
    // 关闭提示
    this.setState({ isShowUpdateVersionTip: false });
  };
  confirmUpdateVersionTip = () => {
    // 提示升级与开始升级
    this.setState({
      isShowUpdateVersionTip: false,
      isShowVersionUpgrading: true,
    });
    Taro.removeStorageSync("isDisconnectUpdate");
  };

  // 完成升级
  wl200UpgradeFinishFun = (isWL200) => {
    let { connectInstrument } = this.state;
    console.log("connectInstrument", connectInstrument);
    let content = "";
    if (isWL200) {
      content = connectInstrument.iotVersionUpgrade;
    } else {
      content = connectInstrument.we200IotVersionUpgrade;
    }
    let nodes = decodeURIComponent(content || "");
    nodes = nodes.replace(/\<img/gi, '<img style="width:100%;height:auto" ');
    nodes = nodes.replace(
      /\<table/gi,
      '<table style="border-spacing: 0;border-collapse: collapse;border: 1px solid #000" '
    );
    nodes = nodes.replace(
      /\<td/gi,
      '<td style="border: 1px solid #000;text-align:center" '
    );
    this.setState({
      isShowVersionUpgrading: false,
      isShowVersionUpgradFinish: true, // 升级介绍
      versionUpgradFinishNodes: nodes,
    });
  };
  // 升级失败
  wl200UpgradeErrorFun = () => {
    this.setState({
      isShowVersionUpgrading: false,
    });
    msg("升级失败");
  };
  // 关闭升级完成公告
  onVersionUpgradFinish = () => {
    this.setState({
      isShowVersionUpgradFinish: false,
    });
  };
  /** iot版本升级 END */

  /**
   * @name 初始化WL200设备护理历史
   * @description 如果存在护理历史，则提示是否连接设备，重新读取
   */
  initDeviceNursingHistory = async () => {
    let WL200NursingHistory = Taro.getStorageSync("WL200NursingHistory");
    if (WL200NursingHistory) {
      this.setState({
        isShowReConnectDeviceRecordWL200: true,
      });
    }
  };

  closeReConnectDeviceRecordWL200 = () => {
    Taro.removeStorageSync("WL200NursingHistory");
    this.setState({
      isShowReConnectDeviceRecordWL200: false,
    });
  };
  confirmReConnectDeviceRecordWL200 = () => {
    let WL200NursingHistory = Taro.getStorageSync("WL200NursingHistory");
    console.log("WL200NursingHistory", WL200NursingHistory);
    this.setState({
      isShowReConnectDeviceRecordWL200: false,
    });

    let item = getStorageSync("instrument_detail");
    this.setState({ connectInstrument: item });
    setTimeout(() => this.bindBlockLeft());
    Taro.setStorageSync("isSyncHistory", true);
  };

  // 扫码绑定必须先完成注册弹窗:确定以后删除扫码缓存,防止死循环
  onUnloginConfirm() {
    this.setState({ showEquipment: false });
    this.removeScanFun();
  }
  onUnloginClose() {
    this.setState({ showEquipment: false });
    this.removeScanFun();
  }

  /**
   * @name 打开公共提示弹窗
   * @description 仅适用于仅提示文字的弹窗
   * @params 传入字符类型数组，不同下标会自动换行
   */
  openCommonError = (text) => {
    this.setState({
      commonErrorText: text,
      isCommonError: true,
    });
  };
  onCommonErrorFun = () => {
    this.setState({
      isCommonError: false,
    });
  };
  render() {
    let {
      show,
      isCommonError,
      commonErrorText,
      calendarComplete,
      calendarInComplete,
      currentDate,
      messagecount,
      sitePopupList,
      isShowPrivacyPopup,
      isNotRegister,
      isShowSiteSwiper,
      isDev,

      bannerList,
      bannerCurrent,
      // 绑定弹窗
      isVisibleBinding,
      isBindingError,
      isBeforeBindingError,
      BeforeBindingErrorText,
      isBindingError203,
      isRegisterBoolean,
      isExchangeBinding,
      instrumentInfo,
      instrumentList,
      ViewAddInstrument,
      showEquipment,

      // 升级弹窗
      isShowUpdateVersionTip,
      isShowVersionUpgrading,
      isShowVersionUpgradFinish,
      versionUpgradFinishNodes,

      // 蓝牙连接
      isConnectShow,
      connectInstrument,
      // 设备存在记录，是否重连
      isShowReConnectDeviceRecordWL200,
    } = this.state;

    return (
      <Block>
        <View catchMove>
          <PopupAlert
            isShow={isCommonError}
            title="提示"
            content={
              <Block>
                {commonErrorText.map((item) => {
                  return <View>{item}</View>;
                })}
              </Block>
            }
            confirmButtonText="知道了"
            textAlgin="center"
            close={this.onCommonErrorFun}
            confirm={this.onCommonErrorFun}
          />
          <PopupConfirm
            isShow={isShowReConnectDeviceRecordWL200}
            isClose
            title="提示"
            zIndex={10020}
            myClassName="level-up"
            content={
              <Block>
                <View>检测到您上一次护理的记录未生成，</View>
                <View>是否重新读取</View>
              </Block>
            }
            cancelButtonText="取消"
            confirmButtonText="连接设备"
            textAlgin="center"
            close={this.closeReConnectDeviceRecordWL200}
            confirm={this.confirmReConnectDeviceRecordWL200}
          />
          <PopupAlert
            isShow={isBindingError}
            title="提示"
            content={
              <Block>
                <View>序列号信息仍在更新，请联系微信小助理</View>
                <View>协助您绑定仪器</View>
              </Block>
            }
            confirmButtonText="知道了"
            textAlgin="center"
            close={this.onBindErrorClose}
            confirm={this.onBindErrorConfirm}
          />
          <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
            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"
            close={this.onBindErrorClose}
            confirm={this.onBindErrorConfirm}
          />
          <PopupAlert
            isShow={isBeforeBindingError}
            title="提示"
            content={
              BeforeBindingErrorText || "您选择的仪器有误，请重新确认选择"
            }
            confirmButtonText="知道了"
            textAlgin="center"
            close={this.onBeforeBindClose}
            confirm={this.onBeforeBindConfirm}
          />

          <PopupAlert
            isShow={isBindingError203}
            title="提示"
            content="序列码已被别人绑定，请联系微信助手"
            confirmButtonText="知道了"
            textAlgin="center"
            close={this.onBindErrorClose203}
            confirm={this.onBindErrorConfirm203}
          ></PopupAlert>

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

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

          {/* IOT相关弹窗 */}
          {isConnectShow && (
            <ConnectionBluetoot
              deviceInfo={connectInstrument}
              close={this.connectionClose}
              confirm={this.connectionConfirm}
              offlineChange={this.offlineChange}
              pairingChange={this.pairingChange}
              upgradeFun={this.upgradeFun}
            />
          )}
          <PopupAlert
            isLarge
            isClose
            isShow={isShowUpdateVersionTip}
            title="提示"
            content={
              <Block>
                <View>检测到设备有升级请求</View>
                <View>是否进行升级？</View>
              </Block>
            }
            textAlgin="center"
            confirmButtonText="确定"
            close={this.cancelUpdateVersionTip}
            confirm={this.confirmUpdateVersionTip}
          />
          {isShowVersionUpgrading && (
            <UpdateIotWL200
              isShow={isShowVersionUpgrading}
              finishFun={this.wl200UpgradeFinishFun}
              errorFun={this.wl200UpgradeErrorFun}
            />
          )}
          <PopupAlert
            isShow={isShowVersionUpgradFinish}
            title="升级内容公告"
            content={
              <Block>
                <View className="nodes">
                  <RichText nodes={versionUpgradFinishNodes} />
                </View>
              </Block>
            }
            confirmButtonText="知道了"
            textAlgin="left"
            isClose
            close={this.onVersionUpgradFinish}
            confirm={this.onVersionUpgradFinish}
          />
          {/* IOT相关弹窗 END */}
        </View>

        <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="index-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="/instrument/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) => {
                    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 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>
        <Popup show={show} className="custom-popup" overlay={false}>
          <View className="popBox">你已绑定所有设备</View>
        </Popup>
      </Block>
    );
  }
}

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