import { message } from 'antd'
import * as service from '../services/index'
import URLS from '../constants/url'

export default {
    namespace: 'user',
    state: {
        list: [],
        filterLabel: ''
    },
    reducers: {
        list(state, action) {
            const { list } = action;
            return { ...state, list }
        },
        setFilterLabel(state, action) {
            const { label } = action;
            return { ...state, filterLabel: label}
        }
    },
    effects: {
        *fetchList(action, { put, call, select }) {
            const user = yield select(state => state.present.user);
            try {
                if(!action.mandatory && user.list.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.USER_LIST
                });
                console.log('请求用户列表', res);
                if(!res.err && res.data.code > 0) {
                    const list = res.data.data.map(d => ({
                        code: d.id+'',
                        userName: d.userName,
                        fullName: d.name,
                        role: d.role === 'admin' ? '管理员' : '普通用户'
                    }));
                    yield put({ type: 'list', list });
                }else {
                    message.error('请求用户列表失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(e);
                message.error('请求用户列表失败');
            }
        },
        *remoteModify(action, { put, call, select }) {
            const body = {};
            try {
                const res = yield call(service.fetch({
                    url: URLS.USER_UPDATE,
                    body
                }));
                console.log('修改用户信息', body, res);
                if(!res.err && res.data.code > 0) {
                    message.success('修改成功');
                }else {
                    console.log(body, res.err || res.data.msg);
                    message.error('修改失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('修改失败');
            }
        }
    },
    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 });
            })
        }
    }
};