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

  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
    },
    setProjects(state, projects) {
      state.projects = projects
    }
  },

  actions: {
    // 退出登录
    logout({ commit }) {
      return logout().then(response => {
        commit('setUser', {})
        commit('setIsLogin', false)
        commit('setRoles', null)
        commit('setPermissions', null)
        commit('projects', [])
        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 }) {
      const obj = await getUserRolesPermissions().then(res => {
        if (res.code === 0) {
          const data = res.data
          let roles = []
          let permissions = []
          let projects = []
          if (data.roles && Array.isArray(data.roles)) {
            roles = data.roles
          }
          commit('setRoles', roles)
          if (data.permissions && Array.isArray(data.permissions)) {
            permissions = data.permissions
          }
          commit('setPermissions', permissions)
          if (data.projects && Array.isArray(data.projects)) {
            projects = data.projects
            commit('setProjects', projects)
          } else {
            commit('setProjects', [])
          }
          return {
            roles,
            permissions,
            projects
          }
        } else {
          return {}
        }
      }).catch(() => {
        commit('setRoles', null)
        commit('setPermissions', null)
        commit('setProjects', [])
        return {}
      })
      return obj
    }
  }
}

export default user
