import {takeLatest} from 'redux-saga';
import {take, call, put, fork, cancel, select, race} from 'redux-saga/effects';
import { fetchList, fetchItem, updateItem } from '../services/admin/authority';
import {message} from 'antd';

function* getList(query) {
    try {
        const {total, list} = yield call(fetchList, query);
        yield put({
            type: 'FETCH_AUTHORITY_LIST_SUCCESS',
            total,
            items: list
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'FETCH_AUTHORITY_LIST_FAILED',
            err,
        });
    }
}

function* watchList() {
    while (true) {
        const {query} = yield take('FETCH_AUTHORITY_LIST');
        yield fork(getList, query);
    }
}

function* getItem(id) {
    try {
        const item = yield call(fetchItem, id);
        yield put({
            type: 'FETCH_AUTHORITY_ITEM_SUCCESS',
            item
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'FETCH_AUTHORITY_ITEM_FAILED',
            err
        });
    }
}

function* watchItem() {
    while (true) {
        const {id} = yield take('FETCH_AUTHORITY_ITEM');
        yield fork(getItem, id);
    }
}

function* editItem(data) {
    try{
        yield call(updateItem, data);
        message.success('修改成功!');
        yield put({
            type: 'UPDATE_AUTHORITY_ITEM_SUCCESS',
            item: data
        });
    }catch(err){
        console.log(err);
        message.error(err);
        yield put({
            type:'UPDATE_AUTHORITY_ITEM_FAILED',
            err
        });
    }
}

function* watchEdit() {
    while (true) {
        yield take('UPDATE_AUTHORITY');
        yield put({
            type: 'UPDATE_AUTHORITY_START'
        });
        const {data} = yield race({
            data: take('UPDATE_AUTHORITY_ITEM'),
            canceled: take('CANCEL_UPDATE_AUTHORITY')
        });

        if (data && data.item) {
            yield fork(editItem, data.item);
        }
        yield put({
            type: 'UPDATE_AUTHORITY_END'
        });
    }
}

export default function*() {
    yield fork(watchList);
    yield fork(watchItem);
    yield fork(watchEdit);
}
