import classnames from "classnames";
import { Component } from "react";

import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import { Block, Button, Image, Text, View } from "@tarojs/components";
/*** redux ***/
import { connect } from "react-redux";
import { setMobile } from "@/store/features/userInfo";
/*** redux end ***/

import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "./register.less";

/** 自定义组件 **/
import Navbar from "../../components/navbar/navbar";
/** 自定义组件 **/

import { GetUserMobile, MpSplashDetail } from "@/utils/Interface";
import { go, msg } from "@/utils/traoAPI";

class Register extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "注册",
      style:
        "width:calc(100% - 100rpx);background:#fff;border-radius: 20rpx;box-shadow: -2rpx 0 12rpx .5rpx rgba(129, 129, 129, 0.1); height: 800rpx; padding: 30rpx;",
      titleHeight: "",
      menu: {},
      isChecked: false,
      isRegister: false,
      isShow: false,
      isButtonDisabled: false,
      userAgreement: "",
      policy: "",
      bg: "",
      showPrivacyPopup: false,
      showPrivacyContent: false,
      // isRead: true,
      fromUrl: "",
    };
  }

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    this.initData();
  }

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

  onDisagreeTap = () => {
    // 关闭小程序
    Taro.exitMiniProgram({});
  };
  onClosePrivacyContentPopup = () => {
    this.setState({
      showPrivacyContent: false,
    });
  };
  handleAgreePrivacyAuthorization = () => {
    this.setState({
      showPrivacyPopup: false,
    });
    // app.globalData.needAuthorization = false;
  };

  onCheck = () => {
    const { isChecked } = this.state;
    this.setState({ isChecked: !isChecked });
  };

  onSubmit = async (event) => {
    if (event.detail.errMsg !== "getPhoneNumber:ok") {
      this.changeGetPhoneNumberBtn();
      return msg("手机号获取失败");
    }

    const { code } = event.detail;

    try {
      let res = await GetUserMobile({ code });
      if (res.data) {
        const mobile = res.data.data;
        Taro.setStorageSync("mobile", mobile);
        this.props.setMobile(mobile);
        this.changeGetPhoneNumberBtn();
        msg("注册成功");
        // 注册成功两秒后跳转个人信息完善页
        setTimeout(() => {
          go("/pages/userInfo/userInfo");
        }, 1000);
      } else {
        msg("请求异常");
      }
    } catch (error) {
      this.changeGetPhoneNumberBtn();
    }
  };

  // 防止重复获取手机号
  changeGetPhoneNumberBtn = () => {
    let { isButtonDisabled } = this.state;
    this.setState({
      isButtonDisabled: !isButtonDisabled,
    });
  };

  onCloseRegister = () => {
    if (!this.state.isRegister) return;
    this.setState({ isRegister: false });
    if (this.state.fromUrl) {
      const url = this.state.fromUrl;
      this.setState({
        fromUrl: "",
      });
      Taro.redirectTo({
        url: decodeURIComponent(url),
      });
    } else {
      go("/pages/userInfo/userInfo");
    }
  };

  onClosePopup = () => {
    this.setState({ isShow: false, userAgreement: null, policy: null });
  };

  onPopup = async (event) => {
    const { type } = event.target.dataset;
    console.log("onPopup", event, type);
  };

  onPrivacyTap = () => {
    // 跳转用户隐私协议
    go("/pages/privacyPolicy/privacyPolicy");
  };

  onUserTap = () => {
    // 跳转用户协议
    go("/pages/userPolicy/userPolicy");
  };

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {
    const { data } = await MpSplashDetail({
      pageNum: 1,
      pageSize: 5,
      type: 2,
    });
    if (data.code === 200) {
      this.setState({ bg: data.rows[0].filePath });
    }
  }

  render() {
    let { isChecked, bg, isButtonDisabled } = this.state;
    return (
      <Block>
        <View>
          <Navbar />
          <View />
          <View className="main">
            <Image className="bg" src={bg} mode="aspectFill" />
          </View>
          <View className="footer">
            <View className="title">注册登录</View>
            <View className="content">
              <View>
                请自行阅读花至小程序
                <Text onClick={this.onUserTap} data-type="agreement">
                  《用户协议》
                </Text>
                、
              </View>
              <View>
                <Text onClick={this.onPrivacyTap} data-type="policy">
                  《隐私政策》
                </Text>
                ，并完成注册登录
              </View>
            </View>
            <Button
              type="primary"
              disabled={!isChecked || isButtonDisabled}
              open-type="getPhoneNumber"
              className={classnames("btn_login")}
              onGetPhoneNumber={this.onSubmit}
              onClick={this.changeGetPhoneNumberBtn}
            >
              快速登录
            </Button>
            <View className="checked_box">
              {isChecked ? (
                <Image
                  onClick={this.onCheck}
                  className="icon"
                  src={require("../../img/welcome/checked.png")}
                />
              ) : (
                <Image
                  onClick={this.onCheck}
                  className="icon"
                  src={require("../../img/welcome/unchecked.png")}
                />
              )}
              <View className="tips" onClick={this.onCheck}>
                我已阅读并同意《用户协议》和《隐私政策》
              </View>
            </View>

            <Image
              className="close"
              mode="widthFix"
              src={require("../../img/close.png")}
              onClick={this.onSkip}
            />
          </View>
        </View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  mobile: state.userInfo.mobile,
});
const mapDispatchToProps = (dispatch) => ({
  setMobile(data) {
    dispatch(setMobile(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Register);
