import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {GetUserInfo,GetUserLoginStatus} from '@/api/user'
const store = new Vuex.Store({
    state:{
        isUserInfoReady:false,
        userData:{},
        schoolid:0,//116810
        userid: 0 ,//116810(kunpark)/117911(yugutou22)
        apptoken:'',
        vesion:'' //standard定义为标准版，标准版无考试模块;saas定义为SAAS版
    },
    mutations:{
        updateUserState(state,data){
            state.userid = data.userid
            state.apptoken = data.apptoken
            state.schoolid = data.schoolid
            state.vesion = data.vesion
            state.isUserInfoReady = true
        },
		updateState(store){
		    /**获取用户信息 */
		    GetUserInfo().then(res=>{
			
		        if(res.result){
		            let data = res.data[0];
		            let hash = Math.ceil(Math.random()*99999999999);
		            data.userFace = `/uploadfiles/avatar/${state.userid}.jpg?${hash}`;
		            store.state.userData = data;
		        }
		
		        store.state.isUserInfoReady = true
		      
		    })
           
            /**获取用户信息 */
            GetUserLoginInfo().then(res=>{
                let islogin = res.islogin === 'true' ? true : false;
                
                if(islogin){
                    store.commit('updateUserState',{
                        userid:res.userid,
                        apptoken:res.apptoken,
                        schoolid:res.schoolid,
                        vesion:res.vesion
                    })
                    
                }else{
                    store.commit('updateUserState',{
                        userid:0,
                        apptoken:"",
                        schoolid:res.schoolid,
                        vesion:res.vesion
                    })
                }
            })
		}
    }
})

/**
 * 有userid时返回
 */
store.ready = function(callback){
    if(this.state.isUserInfoReady ){
        typeof callback === 'function' && callback(this.state)
    }else{
        setTimeout(()=>{
            this.ready(callback)
        },100)
    }
}

GetUserLoginStatus().then(res=>{
	if(res.islogin == 'true'){
		store.commit('updateUserState',{
			userid:res.userid,
            apptoken:res.apptoken,
            schoolid:res.schoolid,
		})
	}else{
        store.commit('updateUserState',{
			userid:0,
            apptoken:'',
            schoolid:0,
		})
    }
})

export default store