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

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

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

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

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

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

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

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);
    }
}


export default function*() {
    yield fork(watchTradeList);
    yield fork(watchTradeItem);
    yield fork(watchAdd);
    yield fork(watchSettlement);
}
