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

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

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

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

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

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

function* watchEdit() {
    while (true) {
        yield take('UPDATE_RESOURCE');
        yield put({
            type: 'UPDATE_RESOURCE_START'
        });
        const {data} = yield race({
            data: take('UPDATE_RESOURCE_ITEM'),
            canceled: take('CANCEL_UPDATE_RESOURCE')
        });

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

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