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

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

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

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

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


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

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

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