import React, { useEffect, useState } from 'react';
import { withRouter } from "react-router-dom";
import { compose } from "redux";
import { connect } from "react-redux";
import LoadingComponent from '@/common/Loading'


function RouteMiddlePage(props) {

    const [isLoading, setLoadingState] = useState(true)

    useEffect(() => {
        let {user, location, history} = props

        if (history.action === 'POP') {
            history.goBack();
            return
        }

        if (!isLoading) {
            return
        }

        if (!user.isFetching) {
            if (user.hasError) {
                history.replace('/passport', {from: location})
                setLoadingState(false)
            } else {
                let {data} = user || {
                    data: {
                        username: '',
                        avatar: '',
                        isVip: false,
                        token: '',
                        email: '',
                        uid: ''
                    }
                }
                if (Object.values(data).every(item => !!item).length !== 0) {
                    history.replace(location.pathname)
                    setLoadingState(false)
                }
            }
        }
    })

    return (
        <div className={'loading-route'}>
            <LoadingComponent isLoading={isLoading}>
                <div></div>
            </LoadingComponent>
        </div>
    );
}

export default compose(
    connect(
        state => ({user: state.user}),
        null
    ),
    withRouter
)(RouteMiddlePage)