import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import Footer from '@/components/Footer';
import Logo from '@/assets/logo.svg';
import LoginForm from './form';
import LoginBanner from './banner';
import styles from './style/index.module.less';
import { getToken } from '@/api/user';
import { setToken } from '@/utils/auth';
import { localGet, localRemove, openWindow } from '@/utils/common';

function Login() {
  const router = useRouter();
  const [isNeedLogin, setIsNeedLogin] = useState(false);
  const handleLogin = async () => {
    const url = new URL(window.location.href);
    const code = url.searchParams.get('code');
    const { origin, pathname } = window.location;

    setIsNeedLogin(code === null);

    if (code) {
      const callbackUrl = `${origin}/`;
      try {
        // 根据code向后端获取token
        const res: any = await getToken({
          authCode: code,
          callbackUrl
        } as any);

        if (res && res.code === 200) {
          // 保存Token
          setToken(res.data as string);
          // 保存用户信息
          // await userStore.info(); // 如果有对应的Redux操作，可以在这里dispatch

          if (localGet('system_name') === 'pc') {
            openWindow(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/isdp/`, {
              target: '_self'
            });
            localRemove('system_name');
            return;
          }
          else {
            router.push('/dashboard/workplace');
          }
        }
      } catch (error) {
        console.error('Login error:', error);
      }
    }
  };

  useEffect(() => {
    document.body.setAttribute('arco-theme', 'light');

    handleLogin();
  }, [router]); // 依赖数组包含router，确保router变化时能正确执行

  return (
    <div className={styles.container}>
      <>
        <div className={styles.logo}>
          <Logo />
          <div className={styles['logo-text']}>Arco Design Pro</div>
        </div>
        <div className={styles.banner}>
          <div className={styles['banner-inner']}>
            <LoginBanner />
          </div>
        </div>
        <div className={styles.content}>
          <div className={styles['content-inner']}>
            {isNeedLogin ? (
              <LoginForm />
            ) : (
              <div className={styles['loading-content']}>
                <h3 className={styles['loading-text']}>获取授权中...</h3>
                <div className={styles['page-loading-warp']}>
                  <div className={`${styles['ant-spin']} ${styles['ant-spin-lg']} ${styles['ant-spin-spinning']}`}>
                    <span className={`${styles['ant-spin-dot']} ${styles['ant-spin-dot-spin']}`}>
                      <i className={styles['ant-spin-dot-item']} />
                      <i className={styles['ant-spin-dot-item']} />
                      <i className={styles['ant-spin-dot-item']} />
                      <i className={styles['ant-spin-dot-item']} />
                    </span>
                  </div>
                </div>
              </div>
            )}
          </div>
          {/*<div className={styles.footer}>*/}
          {/*  <Footer />*/}
          {/*</div>*/}
        </div>
      </>
    </div>
  );
}

Login.displayName = 'LoginPage';

export default Login;