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

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

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

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

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

function* passItem(data){
    try {
        yield call(pass, data);

        yield put({
            type: 'PASS_WITHDRAW_ITEM_SUCCESS',
            status: data.status,
            memo: data.memo
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'PASS_WITHDRAW_ITEM_FAILED',
            err
        });
    }
}
function* watchPassItem() {
    while (true) {
        const {data} = yield take('PASS_WITHDRAW_ITEM');
        yield fork(passItem, data);
    }
}

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