import SysAuthController from '@/services/apis/SysAuthController';
import type { Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { theme } from 'antd';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import { Footer, IconFont, MenuFooter, ThemeSwitch } from './components';
import AvatarDropdown from './components/RightContent/AvatarDropdown';
import RootLayout from './layouts/RootLayout';
import requestConfig, { LOGIN_PATH } from './requestConfig';
import { MenuType } from './services/enums';

/**
 * 是否忽略权限验证页面
 */
const isIgnoreAuthPage = () => {
    const pn = window.location.pathname;
    return [LOGIN_PATH, '/login-auth'].includes(pn);
};

export function rootContainer(container: JSX.Element, args: any) {
    return React.createElement(RootLayout, args, container);
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
    settings?: Partial<LayoutSettings>;
    currentUser?: API.LoginOutput;
    loading?: boolean;
    authCodes?: string[];
    menus?: API.AntMenuOutput[];
    dark?: boolean;
    fetchUserInfo?: () => Promise<API.LoginOutput | undefined>;
}> {
    const fetchUserInfo = async () => {
        const userInfo = await SysAuthController.getLoginUser();
        if (userInfo) {
            return userInfo;
        } else {
            history.push(LOGIN_PATH);
            return undefined;
        }
    };
    // 如果不是登录页面，执行
    if (!isIgnoreAuthPage()) {
        const currentUser = await fetchUserInfo();
        return {
            fetchUserInfo,
            currentUser,
            settings: defaultSettings as Partial<LayoutSettings>,
        };
    }
    return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
    };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
    const { currentUser } = initialState ?? {};
    // const tm = ThemeMode.get();
    const { token } = theme.useToken();
    // const isDark = tm?.themeMode === 'dark' || (tm?.themeMode === 'auto' && isDarkTheme.matches);

    return {
        actionsRender: () => [
            // <QuestionCircleOutlined key="help" onClick={() => {
            //     window.open('/handbook/学校操作手册.pdf');
            // }} />,
            <ThemeSwitch key="theme" />,
            <div key="org" style={{ lineHeight: 1, fontSize: token.fontSize }}>
                {currentUser?.sysOrg?.fullName}
                （机构代码：{currentUser?.sysOrg?.code}）
            </div>
        ],
        avatarProps: {
            src: currentUser?.avatar || '/images/avatar-default.svg',
            title: currentUser?.name ? `${currentUser?.name}（${currentUser.account}）` : '未登录',
            render: (_, avatarChildren) => {
                return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
            },
        },
        headerTitleRender: (logo, title) => {
            const newTitle = React.cloneElement(title as React.ReactElement, {
                style: {
                    fontWeight: 'normal',
                    lineHeight: '30px',
                    fontSize: '20px',
                }
            });
            return (
                <>
                    {logo}
                    {newTitle}
                </>
            );
        },
        footerRender: () => <Footer />,
        onPageChange: () => {
            const { location } = history;
            // 如果没有登录，重定向到 login
            if (!initialState?.currentUser && location.pathname !== LOGIN_PATH) {
                history.push(LOGIN_PATH);
            }
        },
        menuHeaderRender: undefined,
        collapsedButtonRender: false,
        menuFooterRender: (menuProps) => {
            const collapsed = !menuProps?.collapsed;
            return (<MenuFooter collapsed={collapsed} onClick={() => menuProps?.onCollapse?.(collapsed)} />);
        },
        menu: {
            locale: false,
            request: async () => {
                if (isIgnoreAuthPage()) {
                    return [];
                }

                const buildMenus = (pid?: number): MenuDataItem[] => {
                    const ms: MenuDataItem[] = [];
                    currentUser?.menus
                        ?.filter((item) => item.pid === pid)
                        .forEach((item) => {
                            let icon: React.ReactNode | null = null;
                            if (item.icon) {
                                icon = <IconFont icon={item.icon} style={{ fontSize: 14, marginRight: 4 }} />;
                                // icon = <IconFont icon={item.icon} />;
                            }

                            const children = buildMenus(item.id);
                            const mitem: MenuDataItem = {
                                children,
                                hideInMenu: item.menuType === MenuType.BUTTON,
                                name: item.title ?? '',
                                path: item.path ?? '',
                                icon,
                            };
                            ms.push(mitem);
                        });
                    return ms;
                };

                const menus = buildMenus(0);
                return menus;
            },
        },
        token: {
            // 参见ts声明，demo 见文档，通过token 修改样式
            //https://procomponents.ant.design/components/layout#%E9%80%9A%E8%BF%87-token-%E4%BF%AE%E6%94%B9%E6%A0%B7%E5%BC%8F
            bgLayout: token.colorBgLayout,
            // bgLayout: isDark ? 'rgb(57, 63, 74)' : 'rgb(245, 248, 255)',
            header: {
                // colorBgHeader: token.colorPrimaryActive,
                // colorBgHeader: '#001529',
                // colorHeaderTitle: token.colorWhite,
                // colorTextRightActionsItem: token.colorWhite,
            },
            pageContainer: {
                paddingInlinePageContainerContent: 24,
                paddingBlockPageContainerContent: 24,
            },
            sider: {
                // colorBgMenuItemHover: token.colorPrimaryBg,
                colorBgMenuItemSelected: token.colorPrimaryBgHover,
                colorTextMenuSelected: token.colorPrimaryActive,
                colorTextMenu: token.colorText,
                colorTextMenuActive: token.colorTextHeading,
                // colorMenuItemDivider: '#f00'
                // colorTextMenuItemHover: token.colorWhite,
            },
        },
        // 自定义 403 页面
        // unAccessible: <div>unAccessible</div>,
        // 增加一个 loading 的状态
        childrenRender: (children) => {
            // if (initialState?.loading) return <PageLoading />;
            return <>{children}</>;
        },
        ...initialState?.settings,
        title: AppConfig.systemName,
    };
};

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