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: '',
  orgName: '',
  unitName: '',
  roles: [],
  keys: '',
  username: ''
}

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ORGNAME: (state, orgName) => {
    state.orgName = orgName
  },
  SET_UNITNAME: (state, unitName) => {
    state.unitName = unitName
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_kEYS: (state, keys) => {
    state.keys = keys
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password }).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, unitName, orgName, username } = data

        // permission must be a non-empty array
        if (!permission || permission.length <= 0) {
          // 提供临时权限，修复空权限导致死循环
          // permission.push('guest')
          reject('该用户暂无任何权限，请联系管理员分配权限！')
          return
        }
        if (isMenHu()) {
          permission.push('menhu')
        }
        commit('SET_ROLES', permission)
        commit('SET_NAME', nickname)
        commit('SET_AVATAR', avatar)
        commit('SET_UNITNAME', unitName)
        commit('SET_ORGNAME', orgName)
        commit('SET_kEYS', primaryKey)
        commit('SET_USERNAME', username)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

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

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

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

