/**
 * Created by lichb on 2017/2/7.
 */
import {LOGIN_IN, LOGIN_OUT} from '../mutation-types'
import tokens from '@/apis/tokens'
import {getToken,setToken ,removeToken} from '@/utils/auth'



// initial state
const state = {
  tokens: '',
  username:''
}

// getters
const getters = {
  tokens: state => state.tokens,
  username: state => state.username
}

//actions
const actions = {
  login({commit, state}, user){
    // tokens.getTokens(user.name, user.pass).then((data) => {
    tokens.getTokens(user.username, user.password).then((data) => {
      //success
      commit(LOGIN_IN, {data: data.data})
      setToken(data.data.toke)
    }, (error) => {
      //fail
      commit(LOGIN_IN, {data: ''})
      removeToken()
    })
  },
  logout({commit}){
    commit(LOGIN_OUT)
    removeToken()
  }
}

//mutations
const mutations = {
  [LOGIN_IN] (state, {data}) {
    if (data) {
      console.log(data)
      state.tokens = data.toke,
      state.username = data.username
    }
  },
  [LOGIN_OUT] (state) {
    state.tokens = ''
  }
}

//export
export default {
  state,
  getters,
  actions,
  mutations
}
