import { getUser, logout } from '@/api/account'
import { getUserRolesPermissions } from '@/api/system'
import { resetRouter } from '@/router'
const user = {
  state: {
    user: {},
    isLogin: false,
    hasRolesPermissions: false,
    roles: null,
    permissions: null
  },

  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setIsLogin(state, isLogin) {
      state.isLogin = isLogin
    },
    setRoles(state, roles) {
      state.roles = roles
    },
    setPermissions(state, permissions) {
      state.permissions = permissions
    },
    setHasRolesPermissions(state, hasRolesPermissions) {
      state.hasRolesPermissions = hasRolesPermissions
    }
  },

  actions: {
    // 退出登录
    logout({ commit }) {
      return logout().then(response => {
        commit('setUser', {})
        commit('setIsLogin', false)
        resetRouter()
        return response
      })
    },
    // 检测登录状态
    async checkLogin({ commit }) {
      // await getUserGrade()
      //   .then(response => {
      //     commit('setUserGrade', response.data.level)
      //   })
      //   .catch(() => {
      //   })
      const isLogin = await getUser()
        .then(response => {
          commit('setUser', response.data)
          return true
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      commit('setIsLogin', isLogin)
      return isLogin
    },
    // 检测角色权限
    async checkRolesPermissions({ commit }) {
      await getUserRolesPermissions().then(res => {
        if (res.code === 0) {
          const data = res.data
          let roles = []
          let permissions = []
          if (data.roles && Array.isArray(data.roles)) {
            roles = data.roles.forEach(it => it.name)
          }
          commit('setRoles', roles)
          if (data.permissions && Array.isArray(data.permissions)) {
            permissions = data.permissions
          }
          commit('setPermissions', permissions)
        } else {
          // window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
        }
      }).catch(() => {
        commit('setRoles', null)
        commit('setPermissions', null)
      })
    }
  }
}

export default user
