import { ScrollView, View, Image } from "@tarojs/components";
import { FC } from "@tarojs/taro";
import { AtButton, AtCurtain, AtInput } from "taro-ui";
import { AtCurtainProps } from "taro-ui/types/curtain";
import BorderImg from "./line@2x-min.png";
import { useState } from "react";
import {
  createRandomString,
  getSceneUrl,
  NICKNAME_key,
  onValidateField,
  TOKEN_KEY,
} from "../../../../utils";
import WechatIcon from "../../../../images/icon_wechat@2x-min.png";
import {
  setUserInfoApi,
  setVistorName,
  validateNickName,
  wechatLoginApi,
} from "../../../../api";
import baseStore from "../../../../store/base";
import Taro from "@tarojs/taro";
import "./index.scss";

export interface VisitCardProps extends AtCurtainProps {}

const formRules = {
  name: [{ required: true, message: "请输入昵称" }],
};

export const VisitCard: FC<VisitCardProps> = (props) => {
  const [loading, setLoading] = useState(false);
  const [wechatLoading, setWechatLoading] = useState(false);
  const [name, setName] = useState(`云城居民${createRandomString()}`);

  const handleValidate = async () => {
    const errors = await onValidateField(
      {
        name,
      },
      formRules
    );
    let valid = !errors || errors.filter((error) => error.message).length <= 0;

    if (!valid) {
      Taro.showToast({
        icon: "none",
        title: errors[0].message,
      });
      return false;
    }

    await validateNickName(name);

    return true;
  };

  const handleUserInfo = async () => {
    // console.log(e);
    if (!(await handleValidate())) return;

    Taro.login({
      async success({ code }) {
        try {
          setWechatLoading(true);
          Taro.showLoading({
            title: "登陆中...",
          });

          const data = await wechatLoginApi(code);
          Taro.setStorageSync(TOKEN_KEY, data.token);

          await setUserInfoApi({
            id: data.user.id,
            nickName: name,
          });

          Taro.setStorageSync(NICKNAME_key, name);
          baseStore.name = name;
          baseStore.isLogin = true;
          goHomePage();
        } finally {
          setWechatLoading(false);
          Taro.hideLoading();
        }
      },
    });
  };

  const handleVisitor = async () => {
    try {
      if (!(await handleValidate())) return;

      setLoading(true);
      Taro.showLoading({
        title: "登陆中...",
      });

      await setVistorName(name);

      Taro.setStorageSync(NICKNAME_key, name);
      baseStore.name = name;
      goHomePage();
    } finally {
      setLoading(false);
      Taro.hideLoading();
    }
  };

  const goHomePage = () => {
    Taro.navigateTo({
      url:
        "/subModule/pages/iframe/index?url=" +
        encodeURIComponent(getSceneUrl()),
    });
    // @ts-ignore
    props.onClose();
  };

  return (
    <AtCurtain {...props} className="visit-card">
      <View className="visit-card__title">邀请函</View>

      <ScrollView scrollY className="visit-card__inner">
        <View className="first">致：</View>
        <View>
          在这座梦幻的游戏主城中，我们不仅追逐冒险和快乐，更致力于传递爱与温暖。每一次的探索，都是为了点亮他人的心灵，每一步的冒险，都是为了温暖他人的生活。我们欢迎你加入我们的行列，成为这座城市的一员，与我们一起行善，传递爱意。在这里，每一个人都是慈善的使者，每一次游戏都是一次美好的奉献。加入我们，让我们共同创造更美好的世界！
        </View>
        <View>期待你的加入！</View>
        <View className="right">陶乐乐</View>
      </ScrollView>

      <Image className="visit-card__bd" src={BorderImg} mode="widthFix" />

      <View className="visit-card__input">
        {props.isOpened && (
          <AtInput
            value={name}
            className="visit-card__input__input"
            name="name"
            maxLength={6}
            // @ts-ignore
            type="nickname"
            placeholder="请输入6个字以内昵称"
            onChange={(val) => {
              setName(val as string);
            }}
          />
        )}

        <AtButton
          className="visit-card__input__visit"
          circle
          loading={loading}
          onClick={handleVisitor}
        >
          我是游客
        </AtButton>
      </View>

      <AtButton
        loading={wechatLoading}
        className="visit-card__wechat"
        openType="getUserInfo"
        onGetUserInfo={handleUserInfo}
      >
        <Image className="visit-card__wechat__icon" src={WechatIcon} />
        成为云城居民
      </AtButton>
    </AtCurtain>
  );
};
