import { login, logout, getInfo } from '@/api/user'
import { setToken, removeToken } from '../../utils/auth'
import { resetRouter } from '@/router'
import { isMenHu } from '@/utils/utils'
const state = {
  name: '',
  avatar: '',
  roles: [],
  userId: ''
}

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERId: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      const form = new FormData()
      form.append('userName', username.trim())
      form.append('password', password)
      login(form).then(response => {
        const { data } = response
        setToken(data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 该方法值禁止私自调用，只用于全局钩子路由拦截器
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录!')
        }

        sessionStorage.setItem('user', JSON.stringify(data))

        const { permission, nickname, avatar, primaryKey } = data

        // permission must be a non-empty array
        if (!permission || permission.length <= 0) {
          // 提供临时权限，修复空权限导致死循环
          permission.push('guest')
        }
        if (isMenHu()) {
          permission.push('menhu')
        }
        commit('SET_ROLES', permission)
        commit('SET_NAME', nickname)
        commit('SET_AVATAR', avatar)
        commit('SET_USERId', primaryKey)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

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

