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

/*** redux ***/
import { connect } from "react-redux";
import { userRefresh } from "../../store/features/userInfo";
/*** redux end ***/

/** 自定义组件 **/
import AtCalendar from "../../components/calendar";
import PopupPrivacy from "../../components/popup/popup-privacy";
import PopupAlert from "../../components/popup/popup-alert";
import type CustomTabBar from "../../custom-tab-bar";
import Navbar from "../../components/navbar/navbar";
/** 自定义组件 **/

import { Toast } from "@antmjs/vantui";

import { RefreshWxUserInfo, GetNoReadMessageNum } from "../../utils/Interface";

// css引入
import "taro-ui/rn/style/components/calendar.scss";
import "./index.less";
import { go } from "../../utils/traoAPI";

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

  constructor(props) {
    super(props);
    this.state = {
      isShowPrivacyPopup: false,
      // imgUrl: this.app.globalData.imgUrl,
      userinfo: {
        mobile: this.props.mobile,
      },
      connectInstrument: {},
      yiqiinfo: {},
      titleHeight: "",
      menu: {
        top: 44,
        height: 0,
      },
      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"),

      isNotRegister: false, // 是否未注册
      isDev: false, // 正在开发提示
    };
  }

  async onLoad() {
    const isFirst = Taro.getStorageSync("isWelcome");
    if (!isFirst) {
      go("/pages/initiate/initiate");
    }

    const menu = Taro.getMenuButtonBoundingClientRect();
    this.setState({ menu });
  }

  componentDidMount() {}

  componentWillUnmount() {}

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

    this.showInit();
  }

  componentDidHide() {}

  showInit() {
    const isFirst = Taro.getStorageSync("isWelcome");
    if (isFirst) {
      this.checkShowPrivacyPopup();
      this.GetNoReadMessageNum(); // 查询是否有消息
      this.RefreshWxUserInfo();
    }
  }

  // 检测是否弹出隐私协议
  checkShowPrivacyPopup() {
    const isPrivacy = Taro.getStorageSync("isPrivacy");
    if (isPrivacy !== "true") {
      Taro.getPrivacySetting({
        success: (res) => {
          // console.log(res); // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            const isPrivacyPopup = Taro.getStorageSync("isPrivacyPopup");
            if (!isPrivacyPopup) {
              // 隐私确认弹窗
              this.setState({ isShowPrivacyPopup: true });
              Taro.setStorageSync("isPrivacy", "true");
            }
          } else {
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
          }
        },
        fail: () => {},
        complete: () => {},
      });
    }
  }

  // 刷新用户信息
  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 });
    }
  };

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

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

  // 是否已注册
  isRegister() {
    let mobile = Taro.getStorageSync("mobile");
    if (!mobile) {
      this.alertRegister();
      return false;
    }
    return true;
  }

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

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

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

  public alertRegister = () => {
    this.setState({ isNotRegister: true }); // 打开弹窗
    // if (!this.props.mobile) {
    //   this.setState({ isNotRegister: true }); // 打开弹窗
    //   return;
    // } else {
    //   go("/pages/instrument/instrument");
    // }
  };

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

  // 护理记录
  toNursingRecords = () => {
    if (this.isRegister()) {
      // todo
      this.setState({ isDev: true });
    }
  };

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

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

  render() {
    let {
      currentDate,
      isShowPrivacyPopup,
      isNotRegister,
      messagecount,
      isDev,
    } = this.state;
    return (
      <Block>
        <PopupAlert
          isShow={isNotRegister}
          title="提示"
          content="暂未授权注册，请点击注册"
          confirmButtonText="确定"
          textAlgin="center"
          type="1"
          confirm={this.closeAlert}
        />
        <PopupAlert
          isShow={isDev}
          title="提示"
          content="页面正在开发中"
          confirmButtonText="确定"
          textAlgin="center"
          confirm={this.closeDev}
        />
        <PopupPrivacy
          isShow={isShowPrivacyPopup}
          closePrivacy={this.closePrivacy}
        />
        <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"
                ></Image>
                {messagecount ? <View className="tip"></View> : ""}
              </View>
            </Block>
          }
        ></Navbar>
        <View className="index">
          <View className="date-title" onClick={this.toNursingRecords}>
            <Text style={{ fontSize: "26rpx", color: "#666" }}>护理记录</Text>
            <View className="at-icon at-icon-chevron-right"></View>
          </View>
          <View className="bg-while">
            <AtCalendar
              hideArrow={true}
              isSwiper={false}
              currentDate={currentDate}
              maxDate={Date.now()}
              onTimeChange={this.onTimeChange}
            />
          </View>
        </View>
        <View className="infobox5">
          <View
            className={classnames("nurse_plan_box", "flex", "aitems", "sb")}
          >
            <View className="title">前往护理</View>
          </View>
          <View
            className={classnames(
              "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"
                ></View>
                <View className="txt" onClick={this.addNewDevice}>
                  添加新设备
                </View>
              </View>
            </View>
            <View className="tips">您暂时还没有绑定任何设备</View>
          </View>
        </View>
        <Toast id="toast"></Toast>
      </Block>
    );
  }
}

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