import { Component, PropsWithChildren, useEffect, useState } from "react";

import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import { Block, View, Text, Image, Button } from "@tarojs/components";

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

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

import {
  getUserAgreement,
  WCUserLogin,
  getPrivacyAgreement,
  GetUserMobile,
  UserInfoRegister,
  MpLoginDetail,
  MpSplashDetail,
} from "../../utils/Interface";
import { go, msg } from "../../utils/traoAPI";

const app = Taro.getApp();

export default 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: true,
      isRegister: false,
      isShow: false,
      isButtonDisabled: false,
      userAgreement: "",
      policy: "",
      bg: "",
      showPrivacyPopup: false,
      showPrivacyContent: false,
      // isRead: true,
      fromUrl: "",
    };
  }

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // this.checkPrivacy();
    // if(options.fromUrl) {
    //     this.setData({
    //         fromUrl: options.fromUrl
    //     })
    // }
    // if (options.skipby) {
    //     this.setData({
    //         skipby: options.skipby
    //     })
    // }
    // if (!Taro.getStorageSync("token")) {
    //     await this.WCUserLogin();
    // }

    this.initData();
  }

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

  onSkipTap = () => {
    app.globalData.bindCodeSkipRegister = true;
    this.onSkip();
  };

  // checkPrivacy = () => {
  //   const res = compareVersion("2.32.3");
  //   if (res >= 0) {
  //     // 弹出弹窗
  //     Taro.getPrivacySetting({
  //       success: (res) => {
  //         if (res.needAuthorization) {
  //           this.setState({
  //             showPrivacyPopup: true,
  //           });
  //           app.globalData.needAuthorization = true;
  //         }
  //       },
  //       fail: (err) => {},
  //       complete: (res) => {},
  //     });
  //   }
  // };

  onDisagreeTap = () => {
    // 关闭小程序
    Taro.exitMiniProgram({
      success: (res) => {},
      fail: (err) => {},
      complete: (res) => {},
    });
  };
  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.changeGetPhoneNumberBtn();
        msg("注册成功");
        // 注册成功两秒后跳转个人信息完善页
        setTimeout(() => {
          go("/pages/userInfo/userInfo");
        }, 2000);
      }
    } 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);
    // const request =
    //   type === "agreement"
    //     ? await getUserAgreement()
    //     : await getPrivacyAgreement();
    // const { data } = request;
    // if (data.code === 200) {
    //   this.setState({
    //     userAgreement: data.data.data?.user_agreement?.value
    //       ? formatRichText(data.data.data?.user_agreement?.value)
    //       : null,
    //     policy: data.data.data?.user_privacy_agreement?.value
    //       ? formatRichText(data.data.data?.user_privacy_agreement?.value)
    //       : null,
    //     isShow: true,
    //   });
    // }
  };

  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></Navbar>
          <View></View>
          <View className="main">
            <Image className="bg" src={bg} mode="aspectFill"></Image>
          </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
              style={{ opacity: isChecked ? 1 : 0.6 }}
              type="primary"
              disabled={!isChecked || isButtonDisabled}
              open-type="getPhoneNumber"
              className="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>
              ) : (
                <Image
                  onClick={this.onCheck}
                  className="icon"
                  src={require("../../img/welcome/unchecked.png")}
                ></Image>
              )}
              <View className="tips">
                我已阅读并同意《用户协议》和《隐私政策》
              </View>
            </View>

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

          {/* 
          <View className="skip_footer_box">
            <View className="checked_box">
              {isChecked ? (
                <Image
                  onClick={this.onCheck}
                  className="icon"
                  src={require("../../img/welcome/checked.png")}
                ></Image>
              ) : (
                <Image
                  onClick={this.onCheck}
                  className="icon"
                  src={require("../../img/welcome/unchecked.png")}
                ></Image>
              )}
              <View className="tips">
                我已阅读并同意《用户协议》和《隐私政策》
              </View>
            </View>
            <View className="skip_footer">
              <Button
                style="opacity: {{ isChecked ? 1 : .6 }}"
                type="primary"
                disabled={!isChecked}
                open-type="getPhoneNumber"
                className="skip_foorer_autoBtn"
                onGetPhoneNumber={this.onSubmit}
              >
                快速登录
              </Button>
              <View className="skip_foorer_btn" onClick={this.onSkipTap}>
                跳过{" "}
              </View>
            </View>
          </View> */}
        </View>
      </Block>
    );
  }
}
