import { loginApi, getInfoApi, loginOutApi } from '@/api/user'
import { login, getUserInfo, logout } from '@/api/login.js'
const state = () => ({
  token: '', // 登录token
  info: {},  // 用户信息
})

// getters
const getters = {
  token(state) {
    return state.token
  }
}

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token
  },
  infoChange(state, info) {
    state.info = info
  }
}

// 登录验证保存token
const actions = {
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      login(params).then(res => {
        commit('tokenChange', res.data.access_token)
        dispatch('getInfo', { token: res.data.access_token }).then(infoRes => {
          resolve(res.data.access_token)
        }).catch((err)=> {
          // 获取用户信息失败，清除登录状态并刷新
          dispatch('loginOut')
          reject(new Error('获取用户信息失败，请重新登录'))
        })
      }).catch(err => {
        reject(err)
      })
    })
  },

  // 获取用户登录信息
  getInfo({ commit }, params) {
    return new Promise((resolve, reject) => {
      getUserInfo(params).then(res => {
        commit('infoChange', res.data)
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  // 退出登录
  loginOut({ commit }) {
    logout().then(res => {

    }).catch(error => {

    }).finally(() => {
      localStorage.removeItem('tabs')
      localStorage.removeItem('vuex')
      sessionStorage.removeItem('vuex')
      location.reload()
    })
  }
}

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