import "./LoginBox.scss";
import UserApi from "@/apis/userApi";
import Button from "@/component/button";
import APPConfig from "@/config";
import UserHelper from "@/helper/userHelper";
import RouteUtil from "@/utils/routeUtil";
import StorageUtil, { EStorage } from "@/utils/storageUtil";
import { Image, View, Text, Input } from "@tarojs/components";
import { useRequest } from "ahooks";
import {
  parseQueryParams,
  isOuterLink,
  replaceQueryParam,
} from "../../../utils/toolsUtil";
import { useState, useEffect, useImperativeHandle, forwardRef } from "react";
import { AtFloatLayout } from "taro-ui";
import { showToast } from "@tarojs/taro";
import ctyptoUtil from "@/utils/crypto";

// @ts-ignore
const LoginBox = forwardRef((props, ref) => {
  const channelCode = StorageUtil.get(EStorage.channelCode) || "";

  console.log("channelCode 这会儿是什么? ", channelCode)

  useImperativeHandle(ref, () => ({
    handleOpen() {
      handleOpen();
    },
  }));
  const indexInfoResult: any = useRequest(() => {
    return UserApi.getIndexInfoUsingPost({
      params: { appId: APPConfig.APPID },
    }).toData();
  });
  const postJumpUrlResult = () => {
    const params: any = parseQueryParams(indexInfoResult.data.link);
    return UserApi.getJumpUrlPost({
      loading: true,
      data: {
        appId: APPConfig.APPID,
        channelCode: params.channelCode,
        productId: params.productId,
      },
    })
      .toData()
      .then((res: any) => {
        console.log("获取跳转链接结果", res);
        RouteUtil.toWebViewPage({ url: res?.adJumpLink });
      });
  };

  const loginFlowHandler = async () => {
    await UserHelper.UpdateOpenId();
    if (isOuterLink(indexInfoResult?.data.link)) {
      // 如果是外部链接，不用管
      await postJumpUrlResult();
    } else {
      const jumpUrl = channelCode
        ? replaceQueryParam(
            indexInfoResult.data.link,
            "channelCode",
            channelCode
          )
        : indexInfoResult.data.link;

      RouteUtil.toWebViewPage({
        url: jumpUrl,
      });
    }
  };

  const [isSHow, setIsSHow] = useState(false);
  // 打开浮动层的函数
  const handleOpen = () => {
    setShowNum(0);
    setIsSHow(true);
  };
  // 关闭浮动层的函数
  const handleClose = () => {
    setIsSHow(false);
    // setIsGetValidate(false);
    // setTime(10); // 重置倒计时
    setPhone("");
    setValidate("");
    setCheckedPhone(false);
    setChecked(false);
  };
  const [showNum, setShowNum] = useState(0);
  const showNumChange = (val) => {
    if (!checked) {
      showToast({
        title: "请确定已阅读并同意！",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    setShowNum(val);
  };
  const [checked, setChecked] = useState(false);
  const handleCheckboxChange = () => {
    setChecked(!checked);
  };
  const quickLogin = async (e) => {
    if (!checked) {
      showToast({
        title: "请确定已阅读并同意！",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (
      e.detail.code &&
      (await UserHelper.userWxLogin(e.detail.code, channelCode)) === true
    ) {
      handleClose();
      // indexInfoResult.data &&
      //   RouteUtil.toWebViewPage({
      //     url: indexInfoResult.data.link,
      //   });
      // if (UserHelper.callback) {
      //   await UserHelper.callback();
      // }

      loginFlowHandler();
    }
  };
  const [time, setTime] = useState(60);
  const [isGetValidate, setIsGetValidate] = useState(false);
  const [validate, setValidate] = useState("");
  const [phone, setPhone] = useState("");
  const [checkedPhone, setCheckedPhone] = useState(false);
  const phoneChange = () => {
    setCheckedPhone(!checkedPhone);
  };
  const timeChange = (val) => {
    setTime(val);
  };
  const phoneNumChange = (e) => {
    setPhone(e.detail.value);
  };
  const validateChange = (e) => {
    setValidate(e.detail.value);
  };
  useEffect(() => {
    let intervalId: any = null;
    if (isGetValidate && time > 0) {
      intervalId = setInterval(() => {
        timeChange((prevCount) => prevCount - 1);
      }, 1000);
    } else if (time === 0) {
      setIsGetValidate(false);
      clearInterval(intervalId);
    }
    return () => clearInterval(intervalId);
  }, [isGetValidate, time]);

  const isGetValidateChange = async () => {
    if (phone == "") {
      showToast({
        title: "请输入本人实名认证手机号！",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (isPhoneAvailable(phone)) {
      setIsGetValidate(!isGetValidate);
      setTime(60); // 重置倒计时
      let obj = {
        channelCode: channelCode || "hrqbxcx",
        phone: ctyptoUtil.AesEncode(phone),
        sceneType: "register",
      };
      UserApi.sendCode({
        data: { ...obj },
      })
        .h5toData()
        .then((res: any) => {
          showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        });
    } else {
      showToast({
        title: "手机号有误！",
        icon: "none",
        duration: 2000,
      });
    }
  };
  const isPhoneAvailable = (value) => {
    let phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    return phoneReg.test(value);
  };
  const submitClick = () => {
    if (!checkedPhone) {
      showToast({
        title: "请确定已阅读并同意",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (phone == "") {
      showToast({
        title: "请输入本人实名认证手机号",
        icon: "none",
        duration: 2000,
      });
      return;
    } else if (!isPhoneAvailable(phone)) {
      showToast({
        title: "手机号有误",
        icon: "none",
        duration: 2000,
      });
      return;
    } else if (validate == "") {
      showToast({
        title: "验证码不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    let obj = {
      channelCode: channelCode || "hrqbxcx",
      phone: ctyptoUtil.AesEncode(phone),
      sceneType: "register",
      uctrackid: "",
      verifyCode: validate,
    };
    UserApi.login({
      data: { ...obj },
    })
      .h5toData()
      .then(async (res: any) => {
        if (res.code == 1) {
          showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        } else if (res.code == 0) {
          handleClose();
          let obj: any = {
            userId: res.data.userId,
            token: res.data.token,
            userMobile: phone,
          };
          UserHelper.cacheUserInfo(obj);
          // indexInfoResult.data &&
          //   RouteUtil.toWebViewPage({
          //     url: indexInfoResult.data.link,
          //   });
          // if (UserHelper.callback) {
          //   await UserHelper.callback();
          // }
          loginFlowHandler();
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const aggrement = useRequest(() => {
    return UserApi.agreementsUsingPost({
      data: { pageView: "user_center_view" },
    }).toData();
  });
  const goRegPage = () => {
    aggrement.data?.map((p) => {
      if (p.name == "用户服务协议") {
        RouteUtil.toWebViewPage({ url: p.url });
      }
    });
  };
  const goPrivacyPage = () => {
    console.log(aggrement);
    aggrement.data?.map((p) => {
      if (p.name == "隐私政策") {
        RouteUtil.toWebViewPage({ url: p.url });
      }
    });
  };
  const goStudentPage = () => {
    console.log(aggrement);
    aggrement.data?.map((p) => {
      if (p.name == "非学生承诺函") {
        RouteUtil.toWebViewPage({ url: p.url });
      }
    });
  };
  return (
    <AtFloatLayout isOpened={isSHow} onClose={handleClose}>
      {showNum == 0 && (
        <Image
          src={require("@/assets/box-bg.png")}
          className="avatar-image-bg"
        />
      )}
      {showNum == 0 ? (
        <View className="login-introduce">
          <View className="title">
            登录方式选择及隐私政策告知
            <View onClick={handleClose}>
              <Image
                src={require("@/assets/close.png")}
                className="avatar-image"
              />
            </View>
          </View>
          <View className="text">
            为了您正常的使用我们的小程序服务，我们需要处理您的个人信息，具体详见{" "}
            <Text onClick={goPrivacyPage} className="blue">
              《隐私政策》
            </Text>
            。 在您未确认
            <Text onClick={goPrivacyPage} className="blue">
              《隐私政策》
            </Text>
            前，我们不会搜集您的任何信息。
            {/* 当您勾选协议后即标识您已阅读并同意
            <Text onClick={goPrivacyPage} className="blue">
              《隐私政策》
            </Text>
            和
            <Text onClick={goRegPage} className="blue">
              《注册政策》
            </Text>
            上的全部内容 */}
          </View>
          <View className="checkd">
            <View className="checkbox">
              {checked ? (
                <Image
                  onClick={handleCheckboxChange}
                  src={require("@/assets/checkd.png")}
                  className="avatar-image"
                />
              ) : (
                <Image
                  onClick={handleCheckboxChange}
                  src={require("@/assets/check.png")}
                  className="avatar-image"
                />
              )}
              <Text className="agree" onClick={handleCheckboxChange}>
                请确定已阅读并同意
              </Text>
            </View>
            <Text onClick={goPrivacyPage} className="blue">
              《隐私政策》
            </Text>
            <Text onClick={goRegPage} className="blue">
              《用户服务协议》
            </Text>
            <Text className="agree">和</Text>
            <Text onClick={goStudentPage} className="blue">
              《非学生承诺函》
            </Text>
          </View>
          <View>
            {checked ? (
              <Button
                className="index-quck-btn fontsize36"
                openType="getPhoneNumber"
                onGetPhoneNumber={quickLogin}
              >
                一键快捷登录
              </Button>
            ) : (
              <Button
                className="index-quck-btn fontsize36"
                onClick={quickLogin}
              >
                一键快捷登录
              </Button>
            )}
          </View>
          <View onClick={showNumChange.bind(null, 1)} className="other-login">
            输入手机号登录
          </View>
        </View>
      ) : (
        <View className="login-introduce phone-login">
          <View className="title">
            <Text className="text-title">登录诚易融</Text>
            <View onClick={handleClose} className="float">
              <Image
                src={require("@/assets/close.png")}
                className="avatar-image"
              />
            </View>
          </View>
          <View className="input-box">
            <View className="input-phone">
              <Input
                type="text"
                placeholderClass="gray"
                onInput={phoneNumChange}
                value={phone}
                placeholder="请输入本人实名认证手机号"
                maxlength={11}
              />
            </View>
            <View className="input-password">
              <Input
                type="text"
                placeholderClass="gray"
                onInput={validateChange}
                value={validate}
                placeholder="请输入验证码"
                maxlength={6}
              />
              {isGetValidate ? (
                <View className="gray">重新发送 （{time}S）</View>
              ) : (
                <View className="gettime" onClick={isGetValidateChange}>
                  获取验证码
                </View>
              )}
            </View>
          </View>
          <View className="checkd">
            <View className="checkbox">
              {checkedPhone ? (
                <Image
                  onClick={phoneChange}
                  src={require("@/assets/checkd.png")}
                  className="avatar-image"
                />
              ) : (
                <Image
                  onClick={phoneChange}
                  src={require("@/assets/check.png")}
                  className="avatar-image"
                />
              )}
              <Text className="agree" onClick={phoneChange}>
                请确定已阅读并同意
              </Text>
            </View>
            <Text onClick={goPrivacyPage} className="blue">
              《隐私政策》
            </Text>
            <Text onClick={goRegPage} className="blue">
              《用户服务协议》
            </Text>
            和
            <Text onClick={goStudentPage} className="blue">
              《非学生承诺函》
            </Text>
          </View>
          <View>
            <Button className="index-quck-btn fontsize36" onClick={submitClick}>
              立即登录
            </Button>
          </View>
        </View>
      )}
    </AtFloatLayout>
  );
});

export default LoginBox;
