import { routerRedux } from 'dva/router'
import { message } from 'antd'

const code = window.localStorage.getItem('usercode');
const account = window.localStorage.getItem('account');
// const password = window.localStorage.getItem('password');
const name = window.localStorage.getItem('username');
const role = window.localStorage.getItem('userrole');

// const lastPage = window.localStorage.getItem('lastpage');
// window.localStorage.removeItem('lastpage');

export default {
    namespace: 'main',
    state: {
        currentUser: {
            code,
            account,
            // password,
            name,
            role,
        },
        currentPage: '',
    },
    reducers: {
        setPage(state, action) {
            return { ...state, currentPage: action.page || 'home' };
        },
        setCurrentUser(state, action) {
            const { user } = action;
            return { ...state, currentUser: {
                code: user.code,
                account: user.account,
                // password: user.password,
                name: user.name,
                role: user.role
            } };
        }
    },
    effects: {
        * redirect (action, { put }) {
            const { path, reload } = action;
            yield put(routerRedux.push(path || '/'));
            if(reload) {
                window.location.reload();
            }
        },
        * goBack (action, { put }) {
            const { reload, path } = action;
            if(window.history.length === 1) {
                yield put(routerRedux.push(path || '/'));
            }else {
                yield put(routerRedux.goBack());
            }
            if(reload) {
                window.location.reload();
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            message.config({
                top: 60,
                duration: 2,
                maxCount: 3,
            });
            return history.listen(({ pathname, query }) => {
                let page = pathname.match(/\/(\w*)/)[1];
                dispatch({ type: 'setPage', page });
            })
        }
    }
};