import { login, logout, getRoutes } from '@/api/system/user'
import { resetRouter } from '@/router'
import storage from '@/utils/storage'

const state = {
  token: storage.ss.get('vue_template_token') || '',
  user_menu: storage.ss.get('vue_template_user_menu') || [],
  user_perm: storage.ss.get('vue_template_user_perm') || [],
  user_info: storage.ss.get('vue_template_user_info') || {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_MENU: (state, menus) => {
    state.user_menu = menus
  },
  SET_USER_PERM: (state, perms) => {
    state.user_perm = perms
  },
  SET_USER_INFO: (state, info) => {
    state.user_info = info
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(username, password).then(response => {
        const { access_token, username, nickname, user_id, user_dept, user_post, user_role, avatar } = response
        commit('SET_TOKEN', access_token)
        storage.ss.set('vue_template_token', access_token)
        const info = {
          username: username || '',
          nickname: nickname || '',
          avatar: avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          user_id: user_id || '',
          user_dept: user_dept || '',
          user_role: user_role ? user_role.map(role => role.id) : [],
          user_post: user_post || []
        }
        commit('SET_USER_INFO', info)
        storage.ss.set('vue_template_user_info', info)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user routes
  getRoutes ({ commit, state }) {
    let userId = state.user_info.user_id
    return new Promise((resolve, reject) => {
      getRoutes(userId).then(response => {
        const { data } = response
        let perms = data.perms || []
        let routes = data.routes || []
        commit('SET_USER_MENU', routes)
        storage.ss.set('vue_template_user_menu', routes)
        commit('SET_USER_PERM', perms)
        storage.ss.set('vue_template_user_perm', perms)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({ commit, state }) {
    let token = state.token
    return new Promise((resolve, reject) => {
      logout(token).then(response => {
        commit('SET_TOKEN', '')
        commit('SET_USER_MENU', [])
        commit('SET_USER_INFO', {})
        storage.ss.clear()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      storage.ss.clear()
      resolve()
    })
  }
}

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