import { httpServer } from "@/components/httpServer/httpServer.js";
import router from '@/router/index'
export const user = {
    namespaced: true,
    state: {
        userInfo: {
            uuid: "",
            nickname: "",
            headImg: "",
            authority: "",
        },
        typeList:[],
        token: "",
    },
    mutations: {
        setUserInfo(state, userInfo) {
          state.userInfo = userInfo
        },
        setToken(state, token) {
          state.token = token
        },
        setTypeList(state, typeList) {
           state.typeList = typeList
        },
        LoginOut(state) {
            state.userInfo = {}
            state.token = ""
            localStorage.uid = ""
            localStorage.token=""
            sessionStorage.clear()
            if( location.pathname != '/'){
              router.push('/')
            }
        },
        ResetUserInfo(state, userInfo = {}) {
            state.userInfo = {...state.userInfo,
                ...userInfo
            }
        }
    },
    actions: {
        async loadBaseInfo({ commit, router }) {
          let res = await httpServer("User.baseInfo", {})
          if( res.code != 0 && res.code != 200){
            commit('LoginOut', {} )
            return true
          }
          localStorage.uid = res.data.uid
          localStorage.token  = res.data.token
          commit('setUserInfo', res.data)
          commit('setToken', res.data.token)
          return res.data
        },
        async loadTypeList({ commit, router }) {
          let res = await httpServer("Course.getTypeList", {})
          commit('setTypeList', res.data||[])
          return true
        },
        async saveBaseInfo({ commit }, userInfo) {
          commit('ResetUserInfo', userInfo)
        },
        async doLogout({ commit }, userInfo) {
          // let res = await httpServer("Auth.Logout", {} )
          commit('LoginOut', {})
          return true
        },
        async doLogin({ commit }, param ) {
          console.log("loginStart", res )
          let res = await httpServer("Auth.LoginStudy", param )
          if( res.code == 200 ){
            commit('setUserInfo', res.data)
            commit('setToken', res.data.token)
            localStorage.nickname = res.data.nickname;
            localStorage.token = res.data.token;
            localStorage.headImg = res.data.headImg;
            localStorage.uid = res.data.uid;
            return res.data
          }
          return false
        }
    },
    getters: {
        userInfo(state) {
            return state.userInfo
        },
        typeList(state) {
            return state.typeList
        },
        token(state) {
            return state.token
        },

    }
}
