/**
 * Created by suntao on 2020/2/7.
 */
import {LOGIN_IN, LOGIN_OUT, USER_INFO} from '../mutation-types'
import tokens from '@/apis/tokens'
import {getUserLoginInfo } from '@/apis/user'


const login = {
  state: {
    tokens: '',
    username: '',
    roles: []
  },
  mutations: {
    [LOGIN_IN](state, data) {
      if (data) {
        state.tokens = data.toke
        state.username = data.username
      }
    },
    [LOGIN_OUT](state) {
      state.tokens = ''
    },
    [USER_INFO] (state, data) {
      if (data) {
        state.tokens = data.toke
        state.username = data.username
      }
    }
  },
  actions: {
    login({commit, state}, user) {
      tokens.getTokens(user.username, user.password).then((data) => {
        //success
        commit(LOGIN_IN, data.data)
        // setToken(data.data.toke)
      }, (error) => {
        //fail
        commit(LOGIN_IN, '')
        // removeToken()
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserLoginInfo(getToken()).then(response => {
          const data = response.data
          // data.roles = data.rank.indexOf('CHANNEL') !== -1 ? ['channel'] : ['operator']
          // if (data.roleInfo.roleInfos && data.roleInfo.roleInfos[0] && data.roleInfo.roleInfos[0].roleId === 1) {
          //   data.roles.push('admin')
          // }
          // if (data.roles && data.roles.length > 0) {
          //   // commit('SET_ROLES', data.roles)
          // } else {
          //   reject('getInfo: roles must be a non-null array !')
          // }
          commit(USER_INFO, data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout({commit}) {
      commit(LOGIN_OUT)
      // removeToken()
    }
  }
}

//export
export default login
