import { Text, View, Image, Video } from "@tarojs/components";
import Taro, { FC } from "@tarojs/taro";
import { AtButton, AtForm, AtInput } from "taro-ui";
import classNames from "classnames";
import { useEffect, useState } from "react";
import {
  NICKNAME_key,
  TOKEN_KEY,
  createRandomString,
  onValidateField,
} from "../../utils";
import WechatIcon from "../../images/icon_wechat@2x-min.png";
import {
  checkLoginApi,
  setUserInfoApi,
  setVistorName,
  validateNickName,
  wechatLoginApi,
} from "../../api";
import baseStore from "../../store/base";
import "./index.scss";

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

const LoginPage: FC = () => {
  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 (e) => {
    // 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 checkLogin = async () => {
    try {
      Taro.showLoading({
        title: "登录中...",
      });
      const data = await checkLoginApi();

      if (data) {
        baseStore.isLogin = true;
        goHomePage();
      } else {
        Taro.removeStorageSync(TOKEN_KEY);
        Taro.removeStorageSync(NICKNAME_key);
      }
    } finally {
      Taro.hideLoading();
    }
  };

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

  useEffect(() => {
    const token = Taro.getStorageSync(TOKEN_KEY);

    if (token) {
      checkLogin();
    }
  }, []);

  return (
    <View className={classNames("login")}>
      <AtForm
        className="login-main margin-safe-area-bottom"
        onSubmit={handleVisitor}
      >
        <View className="login-main__name">
          <AtInput
            value={name}
            className="login__name-input"
            name="name"
            maxLength={6}
            // @ts-ignore
            type="nickname"
            placeholder="请输入昵称"
            onChange={(val) => {
              setName(val as string);
            }}
          >
            <Text className="login__name-input__num">{name.length}/6</Text>
          </AtInput>

          <AtButton
            loading={loading}
            className="login__visitor"
            formType="submit"
          >
            游客模式
          </AtButton>
        </View>

        <AtButton
          loading={wechatLoading}
          className="login__wechat-login"
          openType="getUserInfo"
          onGetUserInfo={handleUserInfo}
        >
          <Image className="login__wechat-login__icon" src={WechatIcon} />
          微信一键登录
        </AtButton>
      </AtForm>

      <Video
        className="login__bg"
        src="https://houseoss.4dkankan.com/project/wx-csbwg-public/videos/login.mp4"
        autoplay
        loop
        muted
        controls={false}
        objectFit="cover"
      />
    </View>
  );
};

export default LoginPage;
