import Vue from 'vue'
import Vuex from 'vuex'
import { setToken, getToken } from '@/libs/util'
import { getUserInfo } from '@/api/account'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    hasGetInfo: false,
    token: getToken(),
    name: '',
    roleKey: '',
    materialCategoryId: ''
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setName (state, value) {
      state.name = value
    },
    setRoleKey (state, value) {
      state.roleKey = value
    },
    setMaterialCategoryId (state, value) {
      state.materialCategoryId = value
    },
    setHasGetInfo (state, value) {
      state.hasGetInfo = value
    }
  },
  actions: {
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo().then(res => {
            if (res.code === 0) {
              commit('setName', res.result.name)
              commit('setRoleKey', res.result.roleKey)
              commit('setMaterialCategoryId', res.result.materialCategoryId)
              console.log('setName---------------')
              console.log(res.result.name)
              commit('setHasGetInfo', true)
              resolve(res)
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  },
  modules: {
  }
})
