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

const authority = handleActions({
    ['FETCH_AUTHORITY_LIST'](state) {
        delete state.removed;
        delete state.item;
        return {...state, loading: true};
    },
    ['FETCH_AUTHORITY_LIST_SUCCESS'](state, action) {
        return {...state, loading: false, items: action.items, total: action.total};
    },
    ['FETCH_AUTHORITY_LIST_FAILED'](state, action) {
        return {...state, err: action.err, loading: false, items:[], total:0};
    },
    ['FETCH_AUTHORITY_ITEM'](state) {
        return {...state, loading: true};
    },
    ['FETCH_AUTHORITY_ITEM_SUCCESS'](state, action) {
        return {...state, loading: false, item: action.item};
    },
    ['FETCH_AUTHORITY_ITEM_FAILED'](state, action) {
        return {...state, err: action.err, loading: false, item:null};
    },

    ['CREATE_AUTHORITY_ITEM'](state){
        return {...state, loading: true}
    },
    ['CREATE_AUTHORITY_ITEM_SUCCESS'](state, action){
        return {...state, loading: false, item: action.item}
    },
    ['CREATE_AUTHORITY_ITEM_FAILED'](state, action){
        return {...state, err: action.err, loading: false, item:null}
    },

    ['DELETE_AUTHORITY_ITEM'](state){
        return {...state, loading: true}
    },
    ['DELETE_AUTHORITY_ITEM_SUCCESS'](state, action){
        state.items = state.items.filter(item=>item.name!=action.removed);
        return {...state, loading: false, removed:action.removed }
    },
    ['DELETE_AUTHORITY_ITEM_FAILED'](state, action){
        return {...state, err: action.err, loading: false}
    },

    ['UPDATE_AUTHORITY_START'](state){
        return {...state, isEdit: true}
    },
    ['UPDATE_AUTHORITY_END'](state){
        return {...state, isEdit: false}
    },
    ['UPDATE_AUTHORITY_ITEM'](state){
        return {...state, loading: true}
    },
    ['UPDATE_AUTHORITY_ITEM_SUCCESS'](state, action){
        try {
            if (action.item.permissions) {
                action.item.permissions = JSON.parse(action.item.permissions)
            }
        } catch (err) {

        }
        return {...state, loading: false, item: {...state.item, ...action.item}, isEdit: false}
    },
    ['UPDATE_AUTHORITY_ITEM_FAILED'](state, action){
        return {...state, err: action.err, loading: false, isEdit: false}
    },
}, {
    items: [],
    loading: false,
});


export default authority;
