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, getUserInfo } from '@/api/user';
import { setSessionUserInfo, setToken } from '@/utils/auth';
import { localGet, localRemove, openWindow } from '@/utils/common';
import logoImage from '@/public/assets/logo.png';
import store from '@/store';
import { updateUserInfo } from '@/store/user';
import {
  getMyComponents,
  getPubComponents,
  getTeamComponents,
} from '@/api/components';
import { getPublishPage } from '@/api/flow';
import dayjs from 'dayjs';

function Login() {
  const router = useRouter();
  const [isNeedLogin, setIsNeedLogin] = useState(false);

  async function fetchUserInfo() {
    store.dispatch(updateUserInfo({ userLoading: true }));
    const res: any = await getUserInfo();
    setSessionUserInfo(res.data);
    store.dispatch(updateUserInfo({ userInfo: { ...res.data } }));
    getComponentData();
  }

  const getComponentData = async () => {
    try {
      const requests = [
        { promise: getMyComponents(), key: 'myLibs' },
        { promise: getPubComponents(), key: 'pubLibs' },
        { promise: getTeamComponents(), key: 'teamLibs' },
        { promise: getPublishPage(), key: 'pubFlow' },
        // {promise: appId ? getMineSubs({id: appId}) : Promise.resolve(null), key: 'myFlow'},
        // {promise: getEventList(), key: 'eventList'}
      ];

      const obj: any = {
        myLibs: null,
        pubLibs: null,
        teamLibs: null,
        pubFlow: null,
        // myFlow: null,
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      };

      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

      // 分别处理每个请求
      for (const { promise, key } of requests) {
        try {
          const res: any = await promise;
          if (res?.code === 200 && res.data?.length > 0) {
            // if (key === 'myLibs') {
            //   addCompInfo(res.data);
            //   libsStore.setMyLibs(res.data);
            // } else if (key === 'pubLibs') {
            //   addCompInfo(res.data);
            //   libsStore.setPubLibs(res.data);
            // } else if (key === 'teamLibs') {
            //   addCompInfo(res.data);
            //   libsStore.setTeamLibs(res.data);
            // } else if (key === 'pubFlow') {
            //   addCompInfo(res.data, true);
            //   libsStore.setPubFlow(res.data);
            // }
            // else if (key === 'myFlow') {
            //     let newData = formatFlowMy(res.data);
            //     addCompInfo(newData, true);
            //     libsStore.setMyFlow(newData);
            // }
            // else if (key === 'eventList') {
            //   eventStore.setEventList(res.data);
            // }
          }

          // 更新本地存储数据
          obj[key] = res?.data || null;
          sessionStorage.setItem(
            `compLibs${userInfo.userId}`,
            JSON.stringify(obj)
          );
        } catch (error) {
          console.error(`加载${key}失败:`, error);
        }
      }
    } catch (error) {
      console.error('加载组件库失败:', error);
    }
  };

  const handleLogin = async () => {
    const url = new URL(window.location.href);
    const code = url.searchParams.get('code');
    const token = url.searchParams.get('token');
    const { origin, pathname } = window.location;

    setIsNeedLogin(code === null && token === null);

    // 处理 URL 中的 token 参数
    if (token) {
      try {
        // 记录登录状态
        localStorage.setItem('userStatus', 'login');
        // 保存 Token
        setToken(token);
        // 获取用户信息
        // await fetchUserInfo();

        // 清除 URL 中的 token 参数
        url.searchParams.delete('token');
        window.history.replaceState({}, '', url.pathname + url.search);
        // 跳转首页
        window.location.href = '/dashboard/workplace';
        return;
      } catch (error) {
        console.error('Token login error:', error);
      }
    }

    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 {
            fetchUserInfo();
            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}>
          <img width={50} height={50} src={logoImage.src} />
          <div className={styles['logo-text']}>
            工业软件组件化构建开发与运行支撑环境
          </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;
