
import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import type { ConnectProps } from 'umi';
import { Redirect, connect, history } from 'umi';
import { stringify } from 'querystring';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import session from '@/utils/session';

type SecurityLayoutProps = {
    loading?: boolean;
    currentUser?: CurrentUser;
} & ConnectProps;

type SecurityLayoutState = {
    isReady: boolean;
    shouldShowLoading: boolean;
    initialLoadComplete: boolean;
};

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
    state: SecurityLayoutState = {
        isReady: false,
        shouldShowLoading: false,
        initialLoadComplete: false,
    };

    private loadingTimer?: NodeJS.Timeout;

    componentDidMount() {
        const { location } = history;
        const { dispatch } = this.props;

        // 检查是否有缓存的用户信息，避免不必要的加载状态
        const cachedUser = session.get("currentUser");

        // 设置防闪烁定时器，只有加载时间超过300ms才显示loading
        this.loadingTimer = setTimeout(() => {
            if (!this.state.isReady && !this.state.initialLoadComplete) {
                this.setState({
                    shouldShowLoading: true,
                });
            }
        }, 300);

        if (dispatch) {
            dispatch({
                type: 'user/fetch',
                callback: (user) => {
                    // 清除定时器
                    if (this.loadingTimer) {
                        clearTimeout(this.loadingTimer);
                    }

                    if (user.code && location.pathname !== '/user/login') {
                        history.push('/user/login');
                        return;
                    }

                    dispatch({
                        type: 'global/getMenuData',
                        payload: user.ID,
                        callback: (menu) => {
                            if (menu) {
                                this.setState({
                                    isReady: true,
                                    shouldShowLoading: false,
                                    initialLoadComplete: true,
                                });
                            }
                        }
                    });
                }
            });
        } else {
            // 清除定时器
            if (this.loadingTimer) {
                clearTimeout(this.loadingTimer);
            }

            this.setState({
                isReady: true,
                shouldShowLoading: false,
                initialLoadComplete: true,
            });
        }
    }

    componentWillUnmount() {
        if (this.loadingTimer) {
            clearTimeout(this.loadingTimer);
        }
    }

    render() {
        const { isReady, shouldShowLoading, initialLoadComplete } = this.state;
        const { children, currentUser } = this.props;

        // 用户认证规则
        const isLogin = currentUser && currentUser.ID;

        // 如果初始化未完成且需要显示加载状态，才显示骨架屏
        if (!isReady && shouldShowLoading) {
            return <PageLoading />;
        }

        // 如果还在初始化过程中，但不需要显示loading，返回null（避免闪烁）
        if (!isReady && !shouldShowLoading) {
            return null;
        }

        return children;
    }
}

export default connect(({ user, loading }: ConnectState) => ({
    currentUser: user.currentUser,
    loading: false,
}))(SecurityLayout);
