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

export default {
    namespace: 'home',
    state: {
        originData: {
            siderLoading: false,
            menuLoading: false,
            collectionLoading: false,
            menuExpandedKeys: ['-1'],
            menuSelectedKeys: [],
            menuFilterLabel: '',
            menuAutoExpandParent: true,
            menuCollected: [{},{},{},{},{}],
            tabs: [],
            selectedTab: null,
            collectionDashboards: [], // 已收藏报表
            fixedDashboard: null, // 固定到首页的报表
        }
    },
    reducers: {
        setField(state, action) {
            const { name, value } = action;
            let obj = {};
            obj[name] = value;
            return Object.assign({}, state, obj);
        },
        setFields(state, action) {
            const { fields } = action;
            let obj = {};
            fields.map(f => (obj[f.name] = f.value));
            return Object.assign({}, state, obj);
        },
        reset(state, action) {
            return Object.assign({}, state, state.originData);
        },
        addTab(state, action) {
            const { tabs } = state;
            const { tab } = action;
            return Object.assign({}, state, { tabs: tabs.concat([tab]) });
        },
        removeTab(state, action) {
            const { tabs } = state;
            const { tab } = action;
            let idx = tabs.findIndex(t => t.code === tab.code);
            tabs.splice(idx, 1);
            return Object.assign({}, state, { tabs });
        },
        removeTabs(state, action) {
            const { tabs: allTabs } = state;
            const { tabs } = action;
            for(let i = 0; i < tabs.length; i++) {
                let idx = allTabs.findIndex(t => t.code === tabs[i].code);
                allTabs.splice(idx, 1);
            }
            return Object.assign({}, state, { tabs: allTabs });
        },
        removeAllTabs(state, action) {
            return Object.assign({}, state, { tabs: [] });
        },
        setSelectedTab(state, action) {
            return Object.assign({}, state, { selectedTab: action.tab });
        }
    },
    effects: {
        *openTab(action, { select, call, put }) {
            const home = yield select(state => state.present.home);
            const { tabs } = home;
            const { tab } = action;
            if(tabs.findIndex(t => t.code === tab.code) > -1) {
                yield put({ type: 'changeTab', tab: tab });
            }else {
                yield put({ type: 'addTab', tab });
                yield put({ type: 'changeTab', tab: tab });
            }
        },
        *changeTab(action, { select, call, put }) {
            const home = yield select(state => state.present.home);
            const { tabs } = home;
            const { tab } = action;
            let fields = [];

            yield put({ type: 'setSelectedTab', tab });
            let fTab = tabs.find(t => t.code === tab.code);
            if(!fTab) {
                return false;
            }else {
                let data = { ...fTab.config };
                for(let key in data) {
                    fields.push({
                        name: key,
                        value: data[key]
                    })
                }
                yield put({ type: 'dashboardDesigner/reset' });
                yield put({ type: 'dashboardDesigner/silentSetFields', fields: fields });
            }
        },
        *closeTab(action, { select, call, put }) {
            const { tab } = action;
            yield put({ type: 'removeTab', tab });
            const home = yield select(state => state.present.home);
            const { tabs, selectedTab } = home;
            if(selectedTab.code === tab.code && tabs.length > 0) {
                yield put({ type: 'changeTab', tab: tabs[tabs.length - 1] });
            }
        },
        *closeTabs(action, { select, call, put }) {
            const { tabs } = action;

            yield put({ type: 'removeTabs', tabs });
        },
        *closeAllTabs(action, { select, call, put }) {
            const { home } = yield select(state => ({ home: state.present.home }));
            const { tabs, fixedDashboard } = home;
            let rmTabs = [];

            for(let i = tabs.length - 1; i >= 0; i--) {
                if(!fixedDashboard || (tabs[i].code !== fixedDashboard.code)) {
                    rmTabs.push(tabs[i]);
                }
            }
            yield put({ type: 'removeTabs', tabs: rmTabs });
            if(fixedDashboard && rmTabs.length > 0) {
                let sTab = tabs.find(t => t.code === fixedDashboard.code);
                yield put({ type: 'changeTab', tab: sTab });
            }
        },
        *saveCurrentTabDashboardConfig(action, { select, call, put }) {
            const { home, dashboardDesigner } = yield select(state => ({ home: state.present.home, dashboardDesigner: state.present.dashboardDesigner }));
            const { tabs } = home;
            const { code } = action;
            let idx = tabs.findIndex(t => t.code === code);
            if(idx > -1 && !tabs[idx].config) {
                // tabs[idx].config = { ...dashboardDesigner }
                tabs[idx].config = JSON.parse(JSON.stringify(dashboardDesigner)) // 使用深复制
            }
            yield put({ type: 'setField', name: 'tabs', value: tabs });
        },
        *fetchCollectionDashboardList(action, { select, call, put }) {
            try {
                const home = yield select(state => state.present.home);
                const { collectionDashboards } = home;
                const { mandatory } = action;
                if(collectionDashboards.length > 0 && !mandatory) {
                    return false;
                }
                if(!action.silent) {
                    yield put({ type: 'setField', name: 'collectionLoading', value: true });
                }
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_COLLECT_LIST,
                    method: 'GET'
                });
                if(!res.err && res.data.code > 0) {
                    const list = res.data.data.map(d => ({
                        code: d.id + '',
                        name: d.name
                    }));
                    yield put({ type: 'setField', name: 'collectionDashboards', value: list });
                    return list;
                }else {
                    message.error('获取收藏列表失败: ' + (res.err || res.data.msg));
                    return false;
                }
            }catch(e) {
                message.error('获取收藏列表失败: ' + e.message);
            }finally {
                yield put({ type: 'setField', name: 'collectionLoading', value: false });
            }
        },
        *collect(action, { select, put, call }) {
            try{
                const home = yield select(state => state.present.home);
                const { data } = action;
                const { collectionDashboards } = home;
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_COLLECT_ADD + '/' + data.code
                });
                if(!res.err && res.data.code > 0) {
                    collectionDashboards.unshift({ code: data.code, name: data.name });
                    yield put({ type: 'setField', name: 'collectionDashboards', value: collectionDashboards });
                }else {
                    message.error('添加收藏失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                message.error('添加收藏失败: ' + e.message);
            }
        },
        *uncollect(action, { select, put, call }) {
            try{
                const home = yield select(state => state.present.home);
                const { data } = action;
                const { collectionDashboards } = home;
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_COLLECT_REMOVE + '/' + data.code
                });
                if(!res.err && res.data.code > 0) {
                    let idx = collectionDashboards.findIndex(d => d.code === data.code);
                    collectionDashboards.splice(idx, 1);
                    yield put({ type: 'setField', name: 'collectionDashboards', value: collectionDashboards });
                }else {
                    message.error('添加收藏失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                message.error('添加收藏失败: ' + e.message);
            }
        },
        *getFixedDashboard(action, { select, put, call }) {
            const main = yield select (state => state.present.main);
            const { currentUser } = main;
            try{
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_FIXED_GET + '/' + currentUser.code,
                    method: 'GET'
                });
                if(!res.err && res.data.code > 0) {
                    // let fixedDashboard = {
                    //     code: res.data.data ? (res.data.data.code + '') : null,
                    //     name: res.data.data ? (res.data.data.name + '') : null
                    // }
                    let fixedDashboard = res.data.data ? {
                        code: res.data.data['id'] + '',
                        name: res.data.data['name'],
                    } : null;
                    yield put({ type: 'setField', name: 'fixedDashboard', value: fixedDashboard });
                    return fixedDashboard;
                }else {
                    message.error('请求默认报表失败: ' + (res.err || res.data.msg));
                    return null;
                }
            }catch(e) {
                message.error('请求默认报表失败: ' + e.message);
            }
        },
        *onFixedDashboard(action, { select, put, call }) {
            const main = yield select (state => state.present.main);
            const { currentUser } = main;
            const { tab } = action;
            try{
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_FIXED + '/' + currentUser.code + '/' + tab.code
                });
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'setField', name: 'fixedDashboard', value: tab });
                    message.success('已设为默认报表');
                }else {
                    message.error('设为默认报表失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                message.error('设为默认报表失败: ' + e.message);
            }
        },
        *onCancelFixedDashboard(action, { select, put, call }) {
            const main = yield select (state => state.present.main);
            const { currentUser } = main;
            const { tab } = action;
            try{
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_CANCELFIXED + '/' + currentUser.code + '/' + tab.code
                });
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'setField', name: 'fixedDashboard', value: null });
                    message.success('已取消默认报表');
                }else {
                    message.error('取消默认报表失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                message.error('取消默认报表失败: ' + e.message);
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            dispatch({ type: 'reset' });
        }
    }
};