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

function* getList(query) {
    try {
        const {total, list} = yield call(fetchList, query);
        yield put({
            type: 'FETCH_ANNOUNCEMENT_LIST_SUCCESS',
            total,
            items: list
        });
    } 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);
        message.success('修改成功!');
        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) {
        yield take('UPDATE_ANNOUNCEMENT');
        yield put({
            type: 'UPDATE_ANNOUNCEMENT_START'
        });
        const {data} = yield race({
            data: take('UPDATE_ANNOUNCEMENT_ITEM'),
            canceled: take('CANCEL_UPDATE_ANNOUNCEMENT')
        });

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

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