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

export default {
    namespace: 'userGroup',
    state: {
        list: [],
        selectedGroup: null,
        filterLabel: '',
        newOne: {}
    },
    reducers: {
        list(state, action) {
            const { list } = action;
            return { ...state, list };
        },
        add(state, action) {
            const { group } = action;
            let list = state.list;
            list.push(group);
            return Object.assign({}, state, {list});
        },
        modify(state, action) {
            const { group } = action;
            let list = state.list;
            list = list.map(l => {
                if(l.code === group.code) {
                    l.name = group.name;
                    l.description = group.description;
                }
                return l;
            });
            return Object.assign({}, state, {list});
        },
        delete(state, action) {
            const { group } = action;
            let list = state.list;
            for(let i = 0; i < list.length; i ++) {
                if(list[i].code === group.code) {
                    list.splice(i, 1);
                    break;
                }
            }
            return Object.assign({}, state, {list});
        },
        setMemberList(state, action) {
            const { groupCode, memberList } = action;
            let list = state.list;
            list = list.map(l => {
                if(l.code === groupCode) {
                    l.member = memberList
                }
                return l;
            });
            return Object.assign({}, state, {list});
        },
        setFilterLabel(state, action) {
            const { label } = action;
            return { ...state, filterLabel: label};
        },
        setNewModelField(state, action) {
            const { name, value } = action;
            let newOne = state.newOne;
            newOne[name] = value;
            return Object.assign({}, state, { newOne });
        },
        setNewModelFields(state, action) {
            const { fields } = action;
            let newOne = state.newOne;
            for(let i = 0; i < fields.length; i++) {
                newOne[fields[i]['name']] = fields[i]['value'];
            }
            return Object.assign({}, state, {newOne});
        },
        setNewModel(state, action) {
            const { model } = action;
            let newOne = Object.assign({}, model);
            return Object.assign({}, state, {newOne});
        },
        resetNewModel(state, action) {
            return { ...state, newOne: {} };
        },
        setSelectedGroup(state, action) {
            const { group } = action;
            return { ...state, selectedGroup: group };
        },
    },
    effects: {
        *fetchList(action, { put, call, select }) {
            const userGroup = yield select(state => state.present.userGroup);
            try {
                if(!action.mandatory && userGroup.list.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_LIST,
                });
                console.log('请求用户组列表', res);
                if(!res.err && res.data.code > 0) {
                    const list = res.data.data.map(d => ({
                        code: d.id+'',
                        name: d.userGroupName,
                        description: d.userGroupNote,
                        createTime: new Date(d.createDate),
                        member: []
                    }));
                    yield put({ type: 'list', list: list.sort((a, b) => a.createTime - b.createTime) });
                }else {
                    console.log(res.err || res.data.msg);
                    message.error('请求用户组列表失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(e);
                message.error('请求用户组列表失败');
            }
        },
        *remoteAdd(action, { put, call, select }) {
            try {
                const userGroup = yield select(state => state.present.userGroup);
                const { newOne } = userGroup;
                let body = {
                    userGroupName: newOne.name,
                    userGroupNote: newOne.description
                };
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_ADD,
                    body: body
                });
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'add', group: {
                        code: res.data.data,
                        name: newOne.name,
                        description: newOne.description,
                        member: []
                    } });
                    yield put({ type: 'setNewModelField', name: 'visibleDetailBox', value: false });
                    yield put({ type: 'resetNewModel' });
                    message.success('新增成功');
                }else {
                    message.error('新增失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(e);
                message.error('新增失败');
            }
        },
        *remoteModify(action, { put, call, select }) {
            const userGroup = yield select(state => state.present.userGroup);
            const { newOne } = userGroup;
            const body = {
                id: newOne.code,
                userGroupName: newOne.name,
                userGroupNote: newOne.description
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_UPDATE,
                    body
                });
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'modify', group: newOne });
                    // yield put({ type: 'setNewModelField', name: 'visibleBox', value: false });
                    // yield put({ type: 'resetNewModel' });
                    message.success('修改成功');
                }else {
                    message.error('修改失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('修改失败');
            }
        },
        *remoteDelete(action, { put, call, select }) {
            const { group } = action;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_DELETE,
                    body: [group.code]
                });
                console.log('删除用户组', [group.code], res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'delete', group });
                    message.success('删除成功');
                }else {
                    console.log([group.code], res.err || res.data.msg);
                    message.error('删除失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log([group.code], e);
                message.error('删除失败');
            }
        },
        *chageSelectedGroup(action, { put, call, select }) {
            const { group } = action;
            yield put({ type: 'remoteMemberList', groupCode: group.code });
            const userGroup = yield select(state => state.present.userGroup);
            const { list } = userGroup;
            yield put({ type: 'setSelectedGroup', group: list.filter(l => l.code === group.code)[0] });
        },
        *remoteMemberList(action, { put, call, select }) {
            const { groupCode, mandatory } = action;
            const userGroup = yield select(state => state.present.userGroup);
            const { list } = userGroup;
            const group = list.filter(l => l.code === groupCode)[0];
            if(!mandatory && group && group.member.length > 0) {
                return;
            }
            try {
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_MEMBER_LIST,
                    body: groupCode
                });
                console.log('请求用户组成员列表', groupCode, res);
                if(!res.err && res.data.code > 0) {
                    const memberList = res.data.data.map(d => ({
                        code: d.id,
                        name: d.name,
                        role: d.role
                    }));
                    yield put({ type: 'setMemberList', groupCode, memberList });
                }else {
                    message.error('请求用户组成员列表失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(groupCode, e);
                message.error('请求用户组成员列表失败');
            }
        },
        *remoteMemberAdd(action, { put, call, select }) {
            const { user, group } = action;
            const body = {
                userId: user.code,
                userGroupId: group.code
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_MEMBER_ADD,
                    body
                });
                console.log('添加用户组成员', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'remoteMemberList', groupCode: group.code, mandatory: true });
                    yield put({ type: 'setNewModelField', name: 'visibleAddMemberBox', value: false });
                }else {
                    message.error('添加失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('添加失败');
            }
        },
        *remoteMemberDelete(action, { put, call, select }) {
            const { userCode, groupCode } = action;
            const body = {
                userId: userCode,
                userGroupId: groupCode
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.USERGROUP_MEMBER_DELETE,
                    body
                });
                console.log('删除用户组成员', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'remoteMemberList', groupCode, mandatory: true });
                }else {
                    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 });
            })
        }
    }
};