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

const state = {
  token: getToken(),
  user: {},
  roles: [],
  pages: [],
  btns: [],
  isInfo: false

}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_BTNS: (state, btns) => {
    state.btns = btns
  },
  SET_PAGES: (state, pages) => {
    state.pages = pages
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ISINFO: (state, isInfo) => {
    state.isInfo = isInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, uuid, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code: code, uuid: uuid }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        const { pages, btns, roles, user } = response

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_USER', user)
        commit('SET_PAGES', pages)
        commit('SET_BTNS', btns)
        commit('SET_ROLES', roles)
        commit('SET_ISINFO', true)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    commit('SET_TOKEN', '')
    commit('SET_USER', {})
    commit('SET_PAGES', [])
    commit('SET_BTNS', [])
    commit('SET_ROLES', [])
    commit('SET_ISINFO', false)

    removeToken()
    resetRouter()

    // reset visited views and cached views
    // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
    dispatch('tagsView/delAllViews', null, { root: true })
    //
    //   resolve()
    // }).catch(error => {
    //   reject(error)
    // })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER', {})
      commit('SET_PAGES', [])
      commit('SET_BTNS', [])
      commit('SET_ROLES', [])
      commit('SET_ISINFO', false)

      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
}
