/** @format */

import * as React from 'react';
import {message} from 'antd';
import Axios from '../utils/xhr';
import globalContext, {globalInitStateProps} from './globalStore';
import createRoutes from '../router/permission';
import {ACCESS_PATH} from '../const/path';
interface actionTypes {
    type: string;
    payload: any;
}
export const producetAccessReducer = (state: any, action: actionTypes) => {
    switch (action.type) {
        case 'ADD_ACCESS':
            return {
                ...state,
                data: createRoutes(action.payload),
            };
        case 'GET_ACCESS':
            return state;
        default:
            return state;
    }
};

const useAccess = () => {
    //需要优化
    const {access, dispatch} = React.useContext<globalInitStateProps>(globalContext);
    React.useEffect(() => {
        Axios({
            url: ACCESS_PATH,
        })
            .then(data => {
                if (data.code === 0) {
                    return dispatch({
                        type: 'ADD_ACCESS',
                        payload: data.data.access,
                    });
                }
                throw data;
            })
            .catch(err => {
                message.error(err.msg || err.messgae);
            });
    }, []);
    return [access];
};
export default useAccess;
