import api from '../../api/user'
import notification from 'ant-design-vue/es/notification'

const user = {
  state: {
    id: '',
    username: '',
    role: []
  },
  mutations: {
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_ROLE: (state, role) => {
      state.role = role
    }
  },
  actions: {
    // 登录
    Login ({ commit }, user) {
      return new Promise((resolve, reject) => {
        api.login(user.username, user.password)
          .then(data => {
            if (data.role !== 'ADMIN') {
              notification.error({
                message: '错误',
                description: '不是管理员账户',
                key: 'ERROR'
              })
              this.Logout().then(() => {})
              reject('Not admin account')
            } else {
              commit('SET_ID', data.id)
              commit('SET_USERNAME', data.username)
              commit('SET_ROLE', data.role)
              resolve(data)
            }
          })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        api.getUser(this.state.user.id)
          .then(data => {
            if (data.role !== 'ADMIN') {
              notification.error({
                message: '错误',
                description: '不是管理员账户',
                key: 'ERROR'
              })
              this.Logout().then(() => {})
              reject('Not admin account')
            } else {
              commit('SET_ID', data.id)
              commit('SET_USERNAME', data.username)
              commit('SET_ROLE', data.role)
              resolve(data)
            }
          })
      })
    },

    // 登出
    Logout ({ commit }) {
      return new Promise((resolve) => {
        commit('SET_ID', '')
        commit('SET_USERNAME', '')
        commit('SET_ROLE', '')
        api.logout()
          .then(() => {
            resolve()
          })
      })
    }

  }
}

export default user
