import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userAccount: '',
  status: '',
  roles: [],
  userId:0,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_STATE: (state, status) => {
    state.status = status
  },
  SET_NAME: (state, userAccount) => {
    state.userAccount = userAccount
  },
  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) => {
      login({ userAccount: username.trim(), passWord: password }).then(rs => {
        commit('SET_TOKEN', rs.data.token)
        commit('SET_USERID', rs.data.userId)
        if(rs.data.token && rs.data.userId){
          localStorage.setItem('userId', rs.data.userId);
          setToken(rs.data.token)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({userId:localStorage.getItem('userId'),token:state.token}).then(rs => {
        const data=rs.data
        let roles=[]
        if (!data) {
          reject('获取用户信息失败，请重新登录')
        }
        // roles must be a non-empty array
        if (!data.level || data.level.length <= 0) {
          reject('用户权限获取失败')
        }
        if(data.state !== 1){
          reject('用户被禁用')
        }
        if(data.level === 1){
          roles=['admin']
        }else{
          roles=['manage']
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', data.userAccount)
        commit('SET_STATE', data.state)
        resolve(data)
      }).catch(error => {
        reject('登录失败')
      })
    })
  },

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

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

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

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