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

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

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

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

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


function* addItem(data) {
    try{
        const item = yield call(createItem, data);
        message.success('创建成功!');
        yield put({
            type: 'CREATE_ANNOUNCEMENT_ITEM_SUCCESS',
            item: {...item, ...data}
        });
    }catch(err){
        console.log(err);
        message.error(err);
        yield put({
            type:'CREATE_ANNOUNCEMENT_ITEM_FAILED',
            err
        });
    }
}

function* watchAdd() {
    while (true) {
        const {data} = yield take('CREATE_ANNOUNCEMENT_ITEM');
        yield fork(addItem, data);
    }
}

function* editItem(data) {
    try{
        yield call(updateItem, data);
        yield put({
            type: 'UPDATE_ANNOUNCEMENT_ITEM_SUCCESS',
            item: data
        });
    }catch(err){
        console.log(err);
        message.error(err);
        yield put({
            type:'UPDATE_ANNOUNCEMENT_ITEM_FAILED',
            err
        });
    }
}

function* watchEdit() {
    while (true) {
        const {data} = yield take('UPDATE_ANNOUNCEMENT_ITEM');
        yield fork(editItem, data);
    }
}

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