users.js 2.38 KB
import baseApiInterface from '@/api/base'
import manageApiInterface from '@/api/backendManage'
import { getAtoken, setAtoken, removeAtoken } from '@/utils/auth'

// app unid
function getAppList(appName) {
  return new Promise((resolve, reject) => {
    manageApiInterface.menuAppList()
      .then(res => {
        res.data.list_data.forEach(item => {
          if (item.name === appName) {
            resolve(item.unid)
          }
        })
      })
  })
}

// user menu
function getMenuList(appUnid) {
  return new Promise((resolve, reject) => {
    manageApiInterface.menuChildNode(appUnid)
      .then(res => {
        resolve(res)
      })
  })
}

const state = {
  atoken: '',
  name: '',
  userType: '',
  userInfo: {},
  roles: [],
  appUnid: ''
}

const mutations = {
  SET_ATOKEN: (state, atoken) => {
    state.atoken = atoken
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_TYPE: (state, userType) => {
    state.userType = userType
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_APP_UNID: (state, appUnid) => {
    state.appUnid = appUnid
  }
}

const actions = {
  // user login
  login({ commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      baseApiInterface.login(loginInfo)
        .then(res => {
          console.log('login res', res)
          if (res.data.code !== 200 || !res.data.success) {
            reject(res.data.msg)
          } else {
            const { data } = res.data
            commit('SET_ATOKEN', data.atoken)
            commit('SET_NAME', data.user_name)
            commit('SET_USER_TYPE', data.userType)
            commit('SET_USER_INFO', data.user)
            commit('SET_ROLES', data.roles)
            setAtoken(data.atoken)
            resolve(data)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('SET_ATOKEN', '')
      removeAtoken()
      resolve()
    })
  },
  // menu
  async getMenu({ commit }, appName) {
    const appUnid = await getAppList(appName)
    const menuList = await getMenuList(appUnid)
    commit('SET_APP_UNID', appUnid)
    console.log('menuList', menuList)
    return Promise.resolve(menuList)
  }
}

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