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

export default {
    namespace: 'dashboard',
    state: {
        list: [],
        filterLabel: '',
        groupList: [],
        currentGroup: [{
            code: 'all',
            label: '全部分组'
        }],
        groupDirty: false,
        
    },
    reducers: {
        list(state, action) {
            let list = action.list;
            return Object.assign({}, state, {list});
        },
        setFilterLabel(state, action) {
            let { label } = action;
            return Object.assign({}, state, {filterLabel: label});
        }
    },
    effects: {
        *fetchList(action, {select, call, put}) {
            try {
                const dashboard = yield select(state => state.present.dashboard);
                if(!action.mandatory && dashboard.list.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_LIST
                });
                console.log('请求看板列表', res);
                if(!res.err && res.data.code > 0) {
                    const resData = res.data.data;
                    let list = resData.map(d => {
                        let items = d.bdConfiguration ? JSON.parse(d.bdConfiguration) : [];
                        return {
                            code:  d.id+'',
                            name: d.bdName,
                            items: items,
                            description: d.bdNote || '',
                            thumbnail: d.thumbnail,
                            creatorCode: d.createId + '',
                            creatorName: d.createBy,
                            createTime: d.createDate,
                        }
                    })
                    yield put({ type: 'list', list: list });
                }else {
                    message.error('请求看板列表失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('请求看板列表失败: ' + e)
            }
        },
        *remoteDetail(action, { select, call, put }) {
            const code = action.code;
            if(!code){
                return
            }
            try {
                yield put({ type: 'dashboardDesigner/silentSetField', name: 'loading', value: true });
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_DETAIL,
                    body: code
                });
                console.log('解析看板数据', code, res);
                if(!res.err && res.data.code > 0) {
                    const resData = res.data.data;
                    let items = resData.bdConfiguration ? JSON.parse(resData.bdConfiguration) : [];
                    let relationColumns = resData.relationColumns ? JSON.parse(resData.relationColumns) : [];
                    const main = yield select(state => state.present.main);
                    const { currentUser } = main;

                    let data = {
                        code:  resData.id+'',
                        name: resData.bdName,
                        items: items,
                        description: resData.bdNote || '',
                        thumbnail: resData.thumbnail,
                        creatorCode: resData.createId + '',
                        creatorName: resData.createBy,
                        createTime: resData.createDate,
                        dataSources: items.map(item => {
                            if(item.viewType === 'chart') {
                                return {
                                    code: item.dataSourceCode,
                                    name: item.dataSourceName
                                }
                            }else {
                                return null
                            }
                        }).filter(item => !!item),
                        relationColumns: relationColumns,
                        editMode: currentUser.code === resData.createId + ''
                    }

                    let fields = [];
                    for(let key in data) {
                        fields.push({
                            name: key,
                            value: data[key]
                        })
                    }
                    yield put({ type: 'dashboardDesigner/silentSetFields', fields: fields });
                }else {
                    message.error('解析看板错误: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('解析看板错误: ' + e);
            }finally {
                yield put({ type: 'dashboardDesigner/silentSetField', name: 'loading', value: false });
            }
        },
        *remoteAdd(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { name, items, thumbnail, relationColumns } = dashboardDesigner;
                let body = {
                    bdName: name,
                    bdNote: '',
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: thumbnail,
                    relationColumns: JSON.stringify(relationColumns),
                }
                console.log('新增看板', body);
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_ADD,
                    body: body
                });
                console.log('新增看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    message.success('保存成功');
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.log(e);
                message.error('保存失败: ' + e);
            }
        },
        *remoteQucikAdd(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { name, items, thumbnail, description, relationColumns } = dashboardDesigner;
                let body = {
                    bdName: name,
                    bdNote: description,
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: thumbnail,
                    relationColumns: JSON.stringify(relationColumns)
                }
                console.log('快速新增看板', body);
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_ADD,
                    body: body
                });
                console.log('快速新增看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    yield put({ type: 'main/redirect', path: '/dashboard/' + res.data.data });
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.log(e);
                message.error('保存失败: ' + e);
            }
        },
        *remoteModify(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { code, name, items, thumbnail, description, relationColumns } = dashboardDesigner;
                let body = {
                    id: code,
                    bdName: name,
                    bdNote: description,
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: thumbnail,
                    relationColumns: JSON.stringify(relationColumns),
                }
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_UPDATE,
                    body: body
                });
                console.log('修改看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    yield put({ type: 'dashboardDesigner/silentSetField', name: 'dirty', value: false });
                    message.success('保存成功');
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.error(e);
                message.error('保存失败: ' + e);
            }
        },
        *remoteDelete(action, { select, call, put }) {
            const dashboard = yield select(state => state.present.dashboard);
            const code = action.code;
            let list = dashboard.list;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_DELETE,
                    body: [code]
                });
                console.log('删除看板', [code], res);
                if(!res.err && res.data.code > 0) {
                    for(let i = 0; i < list.length; i++) {
                        if(list[i].code === code) {
                            list.splice(i, 1);
                            break;
                        }
                    }
                    yield put({ type: 'list', list: list });
                    message.success('删除成功');
                }else {
                    message.error('删除失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('删除失败: ' + e);
            }
        },
        *share(action, { put, call, select }) {
            const { code, targets } = action;
            const body = {
                stId: code+'',
                type: 'dashboard',
                obj: targets.map(t => ({
                    obId: t.code,
                    objectType: t.isGroup ? '0' : '1'
                }))
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_SHARE,
                    body
                });
                console.log('看板分发', body, res);
                if(!res.err && res.data.code > 0) {
                    message.success('分发成功');
                }else {
                    message.error('分发失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(body, e);
                message.error('分发失败: ' + e);
            }
        },
        *transfer(action, { put, call, select }) {
            const { userCode, dashboardCode } = action;
            const body = {
                userId: userCode,
                id: dashboardCode
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_TRANSFER,
                    body
                });
                console.log('看板移交', body, res);
                if(!res.err && res.data.code > 0) {
                    const dashboard = yield select(state => state.present.dashboard);
                    const list = dashboard.list;
                    for(let i = 0; i < list.length; i++) {
                        if(list[i].code === dashboardCode) {
                            list.splice(i, 1);
                            break;
                        }
                    }
                    yield put({ type: 'list', list });
                    message.success('移交成功');
                }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);
            }
        },
        *addHistory(action, { put, call, select }) {
            const { code } = action;
            const body = {
                tarId: code,
                type: '1'
            };
            try {
               const res = yield call(service.fetch, {
                   url: URLS.HISTORY_ADD,
                   body
               });
               if(res.err || res.data.code <= 0) {
                   message.error('添加看板浏览历史失败: ' + (res.err || res.data.msg));
               }
            }catch(e) {
                console.error(body, e);
                message.error('添加看板浏览历史失败: ' + e);
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history}) {
            return history.listen(({pathname}) => {}
        )}
    }
}