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

import { Component, PropsWithChildren, useEffect, useState } from "react";
import {
  Block,
  View,
  Image,
  Video,
  Swiper,
  SwiperItem,
  RichText,
} from "@tarojs/components";

/** 自定义组件 **/
import PopupAlert from "@/components/popup/popup-alert";
import PopupConfirm from "@/components/popup/popup-confirm";
import Navbar from "@/components/navbar/navbar";

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

import { InstrumentInfo } from "@/utils/Interface";
import {
  setStorageSync,
  getStorageSync,
  go,
  back,
  showModal,
} from "@/utils/traoAPI";

import "./intro.less";

class Intro extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "仪器介绍页",
      current: 0,
      instrument: {},
      introList: [],

      isCommonError: false, // 是否显示通用错误提示
      commonErrorText: [], // 通用错误提示

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

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

      // 设备是否重连弹窗
      isShowReConnectDeviceRecordWL200: false,
    };
  }
  $instance = Taro.getCurrentInstance();

  async onLoad() {}
  componentDidMount() {
    let strObj = getStorageSync("instrument_detail");
    if (strObj) {
      let instrument = strObj;
      this.getInstrumentInfo(instrument.id);
      this.setState({ instrument });
    }
  }
  componentWillMount() {
    // let params = Taro.Current?.router?.params;
    // if (params) {
    //   this.getInstrumentInfo(params.id);
    // }
  }
  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {}

  onChange(event) {
    console.info("onchange", event);
    // const current = event.detail.current;
    // this.setState({ current });
  }

  // 获取设备信息
  getInstrumentInfo = async (id) => {
    let res = await InstrumentInfo.instructionInfo({
      instrumentId: id,
    });
    if (res.data.code === 200) {
      this.setState({ introList: res.data.data });
    }
  };

  toHomePage = () => {
    const url = "/pages/index/index";
    Taro.switchTab({
      url,
    });
  };

  customBack = () => {
    let customBack = this.$instance.router?.params?.customBack;
    if (customBack) {
      Taro.reLaunch({ url: "/pages/index/index" });
      return;
    }
    back();
  };

  // 跳转仪器介绍页
  goNursing = () => {
    let { instrument } = this.state;
    if (instrument.status === 0) {
      this.setState({ connectInstrument: instrument });
      setTimeout(() => this.bindBlockLeft());
    } else {
      // todo
      this.openCommonError([
        "该仪器暂时无法进行在线护理，",
        "请联系微信小助理",
      ]);
    }
  };
  /**
   * @name 打开公共提示弹窗
   * @description 仅适用于仅提示文字的弹窗
   * @params 传入字符类型数组，不同下标会自动换行
   */
  openCommonError = (text) => {
    this.setState({
      commonErrorText: text,
      isCommonError: true,
    });
  };
  onCommonErrorFun = () => {
    this.setState({
      isCommonError: false,
    });
  };

  /** 蓝牙逻辑 */
  bindBlockLeft() {
    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);

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

    setTimeout(() => {
      this.connectionClose();
    }, 100);
  };

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

  //连接完成时数据的回调
  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,
    });
  };

  // 完成升级
  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,
    });
  };
  // 关闭升级完成公告
  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());
  };

  render() {
    let {
      current,
      introList,
      instrument,
      isCommonError,
      commonErrorText,
      isShowReConnectDeviceRecordWL200,
      isConnectShow,
      connectInstrument,
      isShowUpdateVersionTip,
      isShowVersionUpgrading,
      isShowVersionUpgradFinish,
      versionUpgradFinishNodes,
    } = this.state;
    return (
      <Block>
        <Navbar
          titleSlot="仪器介绍"
          isBack
          isCustomBack
          customBack={this.customBack}
        />

        <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}
          />
          {/* 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>
        <View style="position: relative">
          <Swiper
            className="main"
            current={current}
            onChange={this.onChange}
            duration={800}
            indicatorDots={false}
            indicatorColor="#999"
            indicatorActiveColor="#333"
            previousMargin="32rpx"
            nextMargin="32rpx"
          >
            {introList.map((item: any, index: number) => {
              return (
                <SwiperItem key={index}>
                  {item.fileType === "video" ? (
                    <Video className="cover" src={item.file} />
                  ) : (
                    <Image
                      className="cover"
                      src={item.file}
                      mode="aspectFill"
                    ></Image>
                  )}

                  <View className="content">
                    <View className="title">{instrument.name}</View>
                    <View className="text">{item.message}</View>
                  </View>
                </SwiperItem>
              );
            })}
          </Swiper>

          {introList.length && (
            <View className="indicator">
              {introList.map((_item, index) => {
                return (
                  <View
                    key={"indicator_" + index}
                    className={classnames("dot", {
                      "bg-show": current === index,
                    })}
                  />
                );
              })}
            </View>
          )}
        </View>

        <View className="footer flex aitems jcenter">
          <View className="btn" onClick={this.goNursing}>
            马上护理
          </View>
          <View className="btn text" onClick={this.toHomePage}>
            暂不护理
          </View>
        </View>
      </Block>
    );
  }
}

export default Intro;
