import {takeLatest} from 'redux-saga';
import {take, call, put, fork, cancel, select} from 'redux-saga/effects';
import {fetchList, fetchItem, createItem, settlementItem, establish} from '../services/trade';
import {message} from 'antd';
import {watchIndex, watchShow, watchCreate, watchEdit} from './RESTful';

function* settlement(id) {
    try {
        const item = yield call(settlementItem, id);
        message.success('发放成功!');
        yield put({
            type: 'SETTLEMENT_TRADE_ITEM_SUCCESS',
            item
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'SETTLEMENT_TRADE_ITEM_FAILED',
            err,
        });
    }
}

function* watchSettlement() {
    while (true) {
        const {id} = yield take('SETTLEMENT_TRADE_ITEM');
        yield fork(settlement, id);
    }
}

function* establishItem(id) {
    try {
        yield call(establish, id);
        message.success('^.^ 喜大普奔，订单成立了!');
        yield put({
            type: 'ESTABLISH_TRADE_ITEM_SUCCESS',
            item: {
                status: 21
            }
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'ESTABLISH_TRADE_ITEM_FAILED',
            err
        });
    }
}

function* watchEstablishItem() {
    while (true) {
        const {id} = yield take('ESTABLISH_TRADE_ITEM');
        yield fork(establishItem, id);
    }
}


export default function*() {
    const ID = 'TRADE';
    yield fork(watchCreate(ID, createItem));
    yield fork(watchIndex(ID, fetchList));
    yield fork(watchShow(ID, fetchItem));
    yield fork(watchSettlement);
    yield fork(watchEstablishItem);
}
