import { message } from 'antd'
import * as service from '../services/index'
import URLS from '../constants/url'
import moment from 'moment'

export default {
    namespace: 'dataList',
    state: {
        columns: [],
        dataSource: []
    },
    reducers: {
        setColumns(state, action) {
            const { columns } = action;
            return { ...state, columns }
        },
        setDataSource(state, action) {
            const { dataSource } = action;
            return { ...state, dataSource }
        },
        reset(state, action) {
            return { ...state, columns: [], dataSource: [] }
        }
    },
    effects: {
        *remoteDataList(action, { put, call, select }) {
            const { byChart, code } = action;
            const body = code;
            try {
                const res = yield call(service.fetch, {
                    url: byChart ? URLS.DATASOURCE_DATA_LIST_BY_CHART : URLS.DATASOURCE_DATA_LIST,
                    body
                });
                console.log('请求数据列表', body, res);
                if(!res.err && res.data.code > 0) {
                    const { columnConfig, values } = res.data.data;
                    let columns = JSON.parse(columnConfig).map(c => ({
                        title: c.columnLable,
                        dataIndex: c.columnName,
                        render: c.columnType === 'time' ? ((v, r, i) => moment(v).format('YYYY-MM-DD')) : v => v
                    }));
                    let dataSource = values;
                    yield put({ type: 'setColumns', columns });
                    yield put({ type: 'setDataSource', dataSource });
                }else {
                    console.log(body, (res.err || res.data.msg));
                    message.error('请求数据列表失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(body, e);
                message.error('请求数据列表失败: ' + e);
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
            })
        }
    }
};