import { useEffect, useState } from "react";
import { getClientConfig } from "@/app/config/client";
import { useAccessStore } from "@/app/store";
import { api } from "@/app/client/api";
import dayjs from "dayjs";
import { showToast } from "@/app/components/ui-lib";

export type ITokenData = {
  access_token: string;
  token_type: string;
  expires_in: number;
  scope?: string[];
};

/**
 * 使用oauth2登录站点
 */
export const EnsureToken = (props: any) => {
  const accessStore = useAccessStore();
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<any>();

  const config = getClientConfig();

  useEffect(() => {
    const parseToken = () => {
      const url = new URL(window.location.href);
      if (url.hash && url.hash.startsWith("#token=")) {
        try {
          setLoading(true);
          const token = JSON.parse(
            decodeURIComponent(url.hash.substring(7)),
          ) as ITokenData;
          accessStore.setAccessToken({
            accessToken: token.access_token,
            tokenType: token.token_type,
            expiresIn: dayjs().add(token.expires_in, "s").unix(),
          });
          setTimeout(() => {
            setLoading(false);
            url.hash = "";
            window.location.href = url.toString();
          }, 1000);
          return;
        } catch (e) {
          setLoading(false);
          console.log("parse token fail", e);
          showToast("登录异常，请联系管理员处理！");
        }
        return;
      }
      api.user
        .userinfo()
        .then(async (resp) => {
          if (!resp) {
            return;
          }
          if (resp.status == 401) {
            if (config?.authorizeUrl) {
              window.location.href = config?.authorizeUrl;
            } else {
              console.log("login expired");
            }
            return;
          }
          const data = await resp.json();
          if (data.code == 1) {
            accessStore.setLogin(true);
            setUser(data);
          } else {
            console.log("fail", data);
          }
        })
        .catch(() => {})
        .finally(() => {
          setLoading(false);
        });
    };
    parseToken();
    const handler = setInterval(parseToken, 10000);
    return () => {
      clearInterval(handler);
    };
  }, []);

  if (accessStore.isLogin() && user) {
    return <>{props.children}</>;
  }
  return (
    <div>
      <span>加载中，请稍后...</span>
    </div>
  );
};
