import * as types from '../mutation-types'
import {user} from '@/request/api'

const state = () => ({
  token: '', // 登录token
  userInfo: {},  // 用户信息
})

// mutations
const mutations = {

  /* 用户登录,获取token */
  [types.USER_GET_TOKEN](state, info) {
    if (info.code == 101) {
      state.userToken = info.data //token
      localStorage.aynUserToken = info.data //把token放入本地存储
      state.isGetToken = true
    } else {
      state.userToken = ''
      localStorage.aynUserToken = ''
      state.isGetToken = false
    }
    state.loginMessage = info.message //登录的提示信息
  },
  /* 用户登录,获取用户信息 */
  [types.USER_GET_USERINFO](state, info) {
    if (info.code == 101) {            
      state.userInfo = info.data || {} //用户信息
      console.log(state.userInfo);
      state.loginStatus = true //登录状态
    } else {
      state.loginMessage = info.message //登录失败提示信息
    }
  },
  /* 用户退出登录 */
  [types.USER_LOGIN_EXIT](state) {
    state.isGetToken = false
    state.loginStatus = false
    state.userToken = ''
    state.userInfo = ''
    localStorage.aynUserToken = ''
  },

}

// actions
const actions = {
  /* 用户登录,获取token */
  getUserToken: async({commit}, params) => {
    let token = await user.GetUserToken(params) //获取token
    await commit(types.USER_GET_TOKEN, token)
  },

  /* 获取用户信息 */
  getUserInfo: async({commit }) => {
    let result = await user.GetUserInfo() //获取用户信息
    await commit(types.USER_GET_USERINFO, result)
  },

   /* 退出登录 */
  loginOut: ({
    commit
  }) => {
    commit(types.USER_LOGIN_EXIT)
  }
}

const getters = {
  userToken: state => state.userToken,
  userInfo: state => state.userInfo,
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}