import { login, getInfo } from '@/api/account'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Base64 } from 'js-base64'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  id: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    const { success, data, msg } = await login({
      data: {
        account: username.trim(),
        password: Base64.encode(password),
        signInType: 'MOBILE_NUMBER_PASSWORD'
      }
    })
    return new Promise((resolve, reject) => {
      if (success) {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      } else {
        reject(msg)
      }
    })
  },

  // get user info
  async getInfo({ commit, state }) {
    const { success, data } = await getInfo()
    return new Promise((resolve, reject) => {
      if (success) {
        const { roles, name, avatar, introduction } = {
          roles: data.roleList.filter(x => x.code.indexOf('ADMIN') !== -1).map(x => x.code),
          introduction: 'I am a super administrator',
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
          name: 'Super Admin'
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve({ roles, name, avatar, introduction })
        // if ('roles' in data) {
        //   const { roles, name, avatar, introduction } = data
        //   commit('SET_ROLES', roles)
        //   commit('SET_NAME', name)
        //   commit('SET_AVATAR', avatar)
        //   commit('SET_INTRODUCTION', introduction)
        //   resolve(data)
        // } else {
        //   reject(msg)
        // }
      }
    })
  },

  // user logout
  async logout({ commit, state, dispatch }) {
    // const { success, msg } = await logout(state.token)
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

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

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      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 })

      resolve()
    })
  }
}

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