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

  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
    },
    // dynamically modify permissions
    async asyncRouters({ commit, dispatch }, data) {
      resetRouter()
      const roles = this.roles
      console.log(roles)
      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/routesByPermissions', roles, { root: true })
      // dynamically add accessible routes
      router.addRoutes(accessRoutes)
    },
    // 检测登录状态
    async checkRolesPermissions({ commit }) {
      const hasRolesPermissions = await getUserRolesPermissions().then(res => {
        const data = res.data
        let rolePermissionCount = 0
        if (data.roles && Array.isArray(data.roles)) {
          const roles = data.roles.forEach(it => it.name)
          commit('setRoles', roles)
          rolePermissionCount++
        }
        if (data.permissions && Array.isArray(data.permissions)) {
          rolePermissionCount++
          commit('setPermissions', data.permissions)
        }
        return rolePermissionCount === 2
      }).catch(() => {
        commit('setRoles', [])
        commit('setPermissions', [])
        return false
      })
      commit('setHasRolesPermissions', hasRolesPermissions)
      // if (hasRolesPermissions) {
      //   this.asyncRouters()
      // }
      return hasRolesPermissions
    }
  }
}

export default user
