import Vue from 'vue'
import Vuex from 'vuex'

import Util from '../common/util.js'
import Cache from '../common/cache.js'

// modules
import UserModule from './module/user.js'
import ExamineModule from './module/examine.js'

Vue.use(Vuex);//vue的插件机制

const store = new Vuex.Store({
	state: {
		lockData: {},
		accessToken: null,
		activityId: null,
		globalConfig: {}		

	},
	modules: {
		user: UserModule,
		examine: ExamineModule,
	},
	mutations: {
		lock(state, key) {
			state.lockData[key] = Util.getTimestamp(null) + 5
		},
		unlock(state, key) {
			state.lockData[key] = Util.getTimestamp(null) + 2
		},
		setAccessToken(state, accessToken) {
			state.accessToken = accessToken
			Cache.put('accessToken', accessToken)
		},
		delAccessToken(state) {
			state.accessToken = null;
			Cache.remove('accessToken')
		},
		setActivityId(state, activityId) {
			state.activityId = activityId
			Cache.put('activityId', activityId)
		},
		delActivityId(state) {
			state.activityId = null
			Cache.remove('activityId')
		},
		setGlobalConfig(state, config) {
			state.globalConfig = config
			Cache.put('globalConfig', config)  // 缓存5分钟
		},
	},
	getters: {
		isLock(state, key) {
			return key => {
				const lockTime = state.lockData[key]
				const timestamp = Util.getTimestamp(null)
				console.log('isLock', key, lockTime, timestamp)
				if (lockTime && lockTime > timestamp) {
					return true
				}
				return false
			}
		},
		accessToken(state) {
			if (state.accessToken === null) {
				state.accessToken = Cache.get('accessToken')
			}
			return state.accessToken
		},
		activityId(state) {
			if (state.activityId === null) {
				state.activityId = Cache.get('activityId') || 0
			}
			return state.activityId
		},
		isLogin(state) {
			if (state.accessToken === null) {
				state.accessToken = Cache.get('accessToken')
			}
			return !!state.accessToken
		},
		globalConfig(state) {
			if (state.globalConfig === null) {
				state.globalConfig = Cache.get('globalConfig')
			}
			return state.globalConfig
		},
	}
})
export default store
