import { Footer, Question, SelectLang, AvatarDropdown, AvatarName } from '@/components';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import { UserInfo, getCurrentUser as queryCurrentUser } from './services/services/user';
import React, { useEffect, useState } from 'react';
import { TokenStorage } from './services/define/tokenStorage';
import { App, ConfigProvider } from 'antd';
import cusRequest from './request';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
let tokenStorage = new TokenStorage();

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: UserModel.UserInfo;
  loading?: boolean;
  token?: string;
  fetchUserInfo?: (id: number) => Promise<UserModel.UserInfo | undefined>;
  GetUsrInfo?: (id: number) => Promise<UserModel.UserInfo | undefined>;
}> {
  try {
    /**
     * 定义获取用户信息的方法
     * @param id 
     * @returns 
     */
    const fetchUserInfo = async (id: number) => {
      try {
        const msg = await queryCurrentUser(id, {
          skipErrorHandler: true,
        });
        if (msg.code != 1) {
          console.log('获取用户信息失败: ', msg.message);
        } else {
          return msg.data;
        }
      } catch (error) {
        console.log('获取用户信息失败: ', error);
        history.push(loginPath);
      }
      return undefined;
    };

    const GetUsrInfo = async (id: number) => {
      const userInfo = await UserInfo.GetUserInfo(id);
      return userInfo;
    }

    // 如果不是登录页面，执行
    const { location } = history;
    if (location.pathname !== loginPath && !location.pathname.startsWith('/user/register')) {
      let currentUserString = localStorage.getItem('userInfo');
      let currentUser = currentUserString ? JSON.parse(currentUserString) : null;
      let token = localStorage.getItem('token') ?? null;
      if (token == null || currentUser == null) {
        history.push('/user/login');
        return {
          fetchUserInfo,
          GetUsrInfo,
          settings: defaultSettings as Partial<LayoutSettings>,
          token: undefined,
          currentUser: currentUser
        };
      }

      // 重新获取用户信息
      let userInfo = await GetUsrInfo(currentUser.id);
      currentUser = userInfo;
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      return {
        token: token,
        fetchUserInfo,
        GetUsrInfo,
        currentUser,
        settings: defaultSettings as Partial<LayoutSettings>,
      };
    }
    return {
      fetchUserInfo,
      GetUsrInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  } catch (error) {
    console.log(error);
    return {};
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      src: "", // 咱们这里不需要头像
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.nickName,
    },
    footerRender: () => (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
        <span style={{ marginRight: "15px" }}>Copyright 2024 LaiTool Admins</span>
        <a style={{ color: "#333" }} href="https://beian.miit.gov.cn/">蜀ICP备2024079688号-1</a>
      </div>
    ),
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!(localStorage.getItem("userInfo")) && !(localStorage.getItem("token")) && location.pathname !== loginPath) {
        console.log('没有登录，重定向到登录页面')
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    menuHeaderRender: undefined,
    childrenRender: (children) => {
      return (
        <>
          <div style={{ minHeight: `calc(100vh - 50px)` }}>
            {children}
          </div>
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

export function rootContainer(container: React.ReactNode) {
  return (<>
    <ConfigProvider componentSize="middle">
      <App>
        {container}
      </App>
    </ConfigProvider>
  </>)
}

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
  timeout: 60000,
};

const validateToken = async () => {
  return
  const token = await tokenStorage.getToken();
  if (!token) {
    history.push('/user/login');
    return;
  }

  try {
    if (location.href.includes('/user/login')) return;
    await cusRequest('/api/Login/Validate', {
      method: 'GET',
    });
  } catch (error) {
    console.error('Token validation failed:', error);
  }
};

setInterval(validateToken, 1800000);