import Vue from 'vue'
import Vuex from 'vuex'
import mHelper from '@/utils/helper';
import mRouter from '@/utils/router';


Vue.use(Vuex);

const ACCESSTOKEN = uni.getStorageSync('accessToken') || '';
const REFERRER = uni.getStorageSync('referrer') || '';
const REFRESHTOKEN = uni.getStorageSync('refreshToken') || '';

const USER = uni.getStorageSync('user') || {};
const ROLE = uni.getStorageSync('role')

const store = new Vuex.Store({
    // 数据存放
    state: {
        //用户token
        accessToken: ACCESSTOKEN,
        // 用户权限
        role: ROLE,
        //用户信息
        userInfo: USER.member,
        //推荐人
        referrer: REFERRER,
        //小程序openid
        openId: '',
        //网络状态，用于下载提醒
        networkState: 'unknown',
        refreshToken: REFRESHTOKEN
    },
    // store 的计算属性 返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算。
    getters: {
		// 获取网络状态
		networkStatus: state => {
			return state.networkState;
		},
        // 判断用户是否登录
        hasLogin: state => {
            if (state.accessToken) {
                return true;
            } else {
                return false
            }
        },
        hasrole: state=> {
            if (state.role) {
                return state.role
            } else {
                mHelper.toast('该账号无权访问,默认重新登录！')
                uni.hideLoading()
                setTimeout(() => {
                    mRouter.reLaunch({route: '/pages/public/login'})
                }, 1000);
                return
            }
        }
    },
    // 方法函数，一般用于计算state中的数据
    mutations: {
        login(state, provider) {
           
			// state.accessToken=provider.access_token;
			// state.refreshToken=provider.refresh_token;
			// state.userInfo = provider.member;
			state.user = provider;
            uni.setStorageSync('user', provider.token);
            uni.setStorageSync('role',provider.pages)
			// uni.setStorageSync('accessToken', provider.access_token);
			// uni.setStorageSync('refreshToken', provider.refresh_token);
			// uni.setStorageSync('userInfo', provider.member);
        },
        logout(state) {
            state.accessToken = '';
            state.refreshToken = '';
            state.userInfo = {};
            uni.removeStorageSync('accessToken');
            uni.removeStorageSync('refreshToken');
            uni.removeStorageSync('userInfo');
        },
        setReferrer(state, referrer) {
            state.referrer = referrer;
            uni.setStorageSync('referrer', referrer);
        },
        setOpenId(state, openId) {
            state.openId = openId;
            uni.setStorageSync('openId', openId);
        },
        setNetworkState(state, provider) {
            state.networkState = provider;
        }
    },
    // 异步操作
    actions: {
        networkStateChange({commit}, info) {
            commit('setNetworkState', info);
        },
        logout({commit}) {
            commit('logout');
        }
    }
})

export default store
