import Vue from 'vue';
import Vuex from 'vuex';
import http from '../plugins/http';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        code: '',
        userInfo: null,
        roomInfo: null,
        ammeterInfo: {
            rest: 0
        },
        showNavigationBar: false,
        direction: 'forward',
        app: false
    },
    mutations: {
        setCode(state, code) {
            state.code = code;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },
        setRoomInfo(state, roomInfo) {
            state.roomInfo = roomInfo;
        },
        setAmmeterInfo(state, ammeterInfo) {
            state.ammeterInfo = ammeterInfo;
        },
        setShowNavigationBar(state, showNavigationBar) {
            state.showNavigationBar = showNavigationBar;
        },
        updateDirection(state, direction) {
            state.direction = direction;
        },
        setApp(state, app) {
            state.app = app;
        }
    },
    actions: {
        updateRoomInfo(context) {
            return http.http
                .get('/api/mp/getRoomInfo')
                .then(res => {
                    console.log(res);
                    context.commit('setRoomInfo', res);
                    if (res.ammeterType && res.ammeterId) {
                        return http.http
                            .get('/ammeter/get', {
                                type: res.ammeterType,
                                id: res.ammeterId
                            })
                            .then(res => {
                                console.log(res);
                                context.commit('setAmmeterInfo', res);
                            });
                    }
                })
                .catch(e => {
                    console.log(e);
                });
        },
        updateUserInfo(context) {
            return http.http
                .get('user/my')
                .then(res => {
                    console.log(res);
                    context.commit('setUserInfo', res);
                    let pages = getCurrentPages();
                    let currPage = null;
                    if (pages.length) {
                        currPage = pages[pages.length - 1];
                    }
                    if (res.idNo && currPage.route !== 'pages/home') {
                        wx.switchTab({
                            url: '/pages/home'
                        });
                    } else if (!res.idNo && currPage.route !== 'pages/login') {
                        wx.navigateTo({
                            url: 'login'
                        });
                    }
                    return Promise.resolve();
                })
                .catch(e => {
                    console.log(e);
                });
        }
    }
});
