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

const getDefaultState = () => {
  return {
    token: getToken(),
    userBaseInfo: {},
    userId: '',
    roles: [],
    permissions: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_BASEINFO: (state, data) => {
    state.userBaseInfo = data
  },
  SET_USERID: (state, data) => {
    state.userId = data
  },
  SET_ROLES: (state, data) => {
    console.log('console.log(res.roleNames)')
    console.log(data)
    state.roles = data
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

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
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.userName)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  // getInfo({ commit }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo({ type: 0 }).then(res => {
  //       if (!res) {
  //         reject('Verification failed, please Login again.')
  //       }
  //       commit('SET_BASEINFO', res)
  //       commit('SET_ROLES', res)
  //       resolve(res)
  //     })
  //   }).catch(error => {
  //     reject(error)
  //   })
  // },
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo({ type: 0 }).then(res => {
        if (!res) {
          reject('Verification failed, please Login again.')
        }

        if (res.roleNames && res.roleNames.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', res.roleNames)
          commit('SET_PERMISSIONS', res.permissions)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        // const { isAdmin } = res
        // let roles = isAdmin==1 ? ['admin'] : ['editor']
        // roles must be a non-empty array
        // if (!roleNames || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }

        // commit('SET_ROLES', roles)
        commit('SET_BASEINFO', res)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      removeUserName()
      removeUserId()
      resetRouter()
      commit('SET_TOKEN', '')
      commit('SET_BASEINFO', {})
      commit('SET_ROLES', [])
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeUserName()
      removeUserId()
      commit('RESET_STATE')
      resolve()
    })
  }
}

const getters = {
  token(state) {
    return state.token
  },
  userBaseInfo(state) {
    return state.userBaseInfo
  },
  roles(state) {
    return state.roles
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

