
import storage from '../../utils/tool/storage';
import user from '../../user/index';
import $request from '@/utils/request/index';
import car from '@/utils/controls/car';

export default {
    state: {
        user: {}
    },
    getters: {
        isLogin: function (state) {
            return !!state.user.user && state.user.user.token;
        }
    },
    mutations: {
        getUserInfo: function (state) {
            var data = storage.getItem(user.config.storage);
            if (data !== null) {
                user.user = data.data;
                user.user.isLogin = !!user.user.token;
                user.setRole();
                user.beforeTime = data.beforeTime;
                user.updateTime = data.updateTime;
                user.login = new Date().getTime();
                state.user = user.user;
            }
        },
        setUserInfo: function (state, data) {
            var beforeTime = user.beforeTime || 0;
            var nowTime = new Date().getTime();
            if (!state.user.token) {
                beforeTime = nowTime;
                user.beforeTime = beforeTime;
                user.updateTime = beforeTime;
            }
            else {
                user.updateTime = user.updateTime || 0;
            }
            storage.setItem(user.config.storage, {
                data: data,
                beforeTime: beforeTime,
                updateTime: user.updateTime
            }, user.config.noLogin <= 0 ? -1 : (user.config.noLogin * 24 * 60 * 60 - parseInt(String((nowTime - beforeTime) / 1000))));
            user.user = data;
            user.setRole();
            data.isLogin = !!data.token;
            state.user = data;
        },
        clearUserInfo: function (state) {
            state.user = {};
            user.user = {};
            user.beforeTime = 0;
            user.login = 0;
            car.setCartNumber(0);
            return storage.removeItem(user.config.storage);
        }
    },
    actions:{
        updateUserInfoPromise({commit},updated=false){

            return new Promise((resolve, reject)=>{
                $request({
                    url:'user/getUserInfo',
                    token:true,
                    login:false
                }).then((data)=>{
                    data = data.data || {};
                    data = {
                        ... user.user,
                        ...data,
                        ...data.userInfo
                    }
                    delete data.userInfo;
                    commit('setUserInfo',data);
                }).catch(reject);
            });
        }
    }
}
