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


const code = window.localStorage.getItem('usercode');
const account = window.localStorage.getItem('account');
const password = window.localStorage.getItem('password');
const name = window.localStorage.getItem('username');
const role = window.localStorage.getItem('userrole');

export default {
    namespace: 'main',
    state: {
        authenticated: false,
        currentUser: {
            code,
            account,
            password,
            name,
            role,
        },
        currentPage: '',
        recentChart: [],
        recentDashboard: []
    },
    reducers: {
        setPage(state, action) {
            return { ...state, currentPage: action.page || 'home' };
        },
        setCurrentUser(state, action) {
            const { user } = action;
            return { ...state, currentUser: {
                code: user.code,
                account: user.account,
                // password: user.password,
                name: user.name,
                role: user.role
            } };
        },
        setAuthenticated(state, action) {
            const { authenticated } = action;
            return { ...state, authenticated };
        },
        listRecentChart(state, action) {
            const { recentChart } = action;
            return { ...state, recentChart };
        },
        listRecentDashboard(state, action) {
            const { recentDashboard } = action;
            return { ...state, recentDashboard };
        }
    },
    effects: {
        * redirect (action, { put }) {
            const { path, reload } = action;
            yield put(routerRedux.push(path || '/'));
            if(reload) {
                window.location.reload();
            }
        },
        * goBack (action, { put }) {
            const { reload, path } = action;
            if(window.history.length === 1) {
                yield put(routerRedux.push(path || '/'));
            }else {
                yield put(routerRedux.goBack());
            }
            if(reload) {
                window.location.reload();
            }
        },
        *logout( action, { put, call, select }) {
            try {
                window.localStorage.removeItem("username");
                window.localStorage.removeItem("userrole");
                window.localStorage.removeItem("usercode");
                window.localStorage.removeItem("loginTime");
                window.localStorage.removeItem("token");
                window.localStorage.removeItem("expireTime");
                yield put({ type: 'dataConnect/list', list: [] });
                yield put({ type: 'dataSource/list', list: [] });
                yield put({ type: 'chart/list', list: [] });
                yield put({ type: 'dashboard/list', list: [] });
                yield put({ type: 'user/list', list: [] });
                yield put({ type: 'userGroup/list', list: [] });
            }catch(e) {
                console.log(e);
                message.error('注销失败: ' + e);
            }
        },
        *fetchRecentChart(action, { select, call, put }) {
            const body = {};
            try {
                const main = yield select(state => state.present.main);
                if(!action.mandatory && main.recentChart.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_RECENT_CHART_GET,
                    body
                });
                
                console.log('请求最近访问图表', body, res);
                if(!res.err && res.data.code > 0) {
                    let recentChart = res.data.data.map((r, i) => {
                        return {
                            key: r.chartId,
                            code: r.chartId,
                            name: r.chartName,
                            type: r.chartType,
                            createBy: r.createBy,
                            chartOption: r.chartOption,
                            description: r.describes || "",
                            createTime: r.createDate,
                        }
                    });
                    yield put({ type: 'listRecentChart', recentChart });
                }else {
                    message.error('读取最近访问图表列表错误: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('读取最近访问图表列表错误: ' + e);
            }
        },
        *fetchRecentDashboard(action, { select, call, put }) {
            const body = {};
            try {
                const main = yield select(state => state.present.main);
                if(!action.mandatory && main.recentDashboard.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_RECENT_DASHBOARD_GET,
                    body
                });
                console.log('请求最近访问看板', body, res);
                if(!res.err && res.data.code > 0) {
                    let recentDashboard = res.data.data.map((r, i) => {
                        return {
                            key: r.id,
                            code: r.id,
                            name: r.bdName,
                            thumbnail: r.thumbnail,
                            createBy: r.createBy,
                            description: r.bdNote || ""
                        }
                    });
                    yield put({ type: 'listRecentDashboard', recentDashboard });
                }else {
                    message.error('读取最近访问看板列表错误: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('读取最近访问看板列表错误: ' + e);
            }
            
        },
        *addRecentRecord(action, { call }) {
            const { tarId, recordType } = action
            console.log(tarId, recordType)
            try {
                const res = yield call(service.fetch, {
                    url: URLS.HOMEPAGE_ADD_RECENT_RECORD,
                    body: {
                        tarId: tarId,
                        type: recordType
                    }
                });
                console.log("添加访问记录: " + res + tarId, recordType)
            }catch(e) {
                console.log(e);
                message.error('添加访问记录错误: ' + e);
            }


        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            message.config({
                top: 60,
                duration: 2,
                maxCount: 3,
            });
            return history.listen(({ pathname, query }) => {
                let page = pathname.match(/\/(\w*)/)[1];
                dispatch({ type: 'setPage', page });
            })
        }
    }
};