import { login, logout, getInfo } from '@/api/app/user'
import { getToken, setToken, removeToken } from '@/assets/js/utils/auth'

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

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

const actions = {
  getSid({ commit }, data) {
    commit('SET_SID', data)
  },
  setGroupList({ commit }, data) {
    commit('SET_GROUPLIST', data)
  },
  setToken({ commit }, data) {
    commit('SET_TOKEN', data)
  },
  removeRoles({ commit }) {
    commit('SET_ROLES', [])
  },
  // user login
  login({ commit }, userInfo) {
    const { userName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), password: password })
        .then(res => {
          setToken(res.content.content)
          commit('SET_TOKEN', res.content.content)
          // getInfo()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(res => {
          let roles = res.content.content.roleCodes || []
          if (roles && roles.length > 0) {
            // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles)
          }
          sessionStorage.setItem(
            'userInfo',
            JSON.stringify(res.content.content)
          )
          commit('SET_NAME', res.content.content.userName)
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

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

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