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

function* getItem(id) {
    try {
        const {trade, shipping} = yield call(fetchItem, id);
        yield put({
            type: 'FETCH_CONTRACT_ITEM_SUCCESS',
            trade,
            shipping
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'FETCH_CONTRACT_ITEM_FAILED',
            err,
        });
    }
}

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

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

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

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

