import {handleActions} from 'redux-actions';
import {combineReducer} from 'redux';

let _user = sessionStorage.getItem('user');
try {
    _user = JSON.parse(_user);
    if (_user && Date.now() - _user.time < 24 * 3600000) {
        _user = _user.data;
    } else {
        _user = {};
    }
} catch (ex) {
    _user = {};
}

const user = handleActions({
    ['LOGIN_REQUEST'](state) {
        return {...state, loading: true};
    },
    ['LOGIN_SUCCESS'](state, action) {
        return {...state, loading: false, ...action.user};
    },
    ['LOGIN_ERROR'](state, action) {
        return {...state, err: action.err, loading: false};
    },
    ['LOGOUT'](state) {
        return {...state, auth: {}, loading: false};
    },

    ['CREATE_USER'](state){
        return {...state, loading: true};
    },
    ['CREATE_USER_SUCCESS'](state, action){
        return {...state, loading: false, created: action.result.id};
    },
    ['CREATE_USER_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

    ['FETCH_USER_LIST'](state){
        return {...state, loading: true};
    },
    ['FETCH_USER_LIST_SUCCESS'](state, action){
        return {...state, loading: false, items: action.items, total: action.total};
    },
    ['FETCH_USER_LIST_FAILED'](state, action){
        return {...state, loading: false, err: action.err, items: [], total: 0};
    },

    ['FETCH_USER_ITEM'](state){
        return {...state, loading: true};
    },
    ['FETCH_USER_ITEM_SUCCESS'](state, action){
        return {...state, loading: false, item: action.item};
    },
    ['FETCH_USER_ITEM_FAILED'](state, action){
        return {...state, loading: false, err: action.err, item: null};
    },

    ['UPDATE_USER_START'](state){
        return {...state, isEdit: true}
    },
    ['UPDATE_USER_END'](state){
        return {...state, isEdit: false}
    },
    ['UPDATE_USER_ITEM'](state){
        return {...state, loading: true};
    },
    ['UPDATE_USER_ITEM_SUCCESS'](state, action){
        return {...state, loading: false, item: {...state.item, ...action.item}, isEdit: false};
    },
    ['UPDATE_USER_ITEM_FAILED'](state, action){
        return {...state, loading: false, err: action.err, isEdit: false};
    },
    ['MODIFY_USER_PASSWORD'](state){
        return {...state, loading: true};
    },
    ['MODIFY_USER_PASSWORD_SUCCESS'](state){
        return {...state, loading: false};
    },
    ['MODIFY_USER_PASSWORD_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

}, {
    ..._user,
    loading: false,
});

export default user;
