import axios from 'axios'

export default {
  namespaced: true,
  state: {
    current: {}
  },
  mutations: {
    setCurrent (state, current) {
      state.current = current
    }
  },
  actions: {
    async login ({commit, dispatch}, data) {
      let result = await axios.post('/auth/login', data)
      switch (result.status) {
        case 200:
          commit('setCurrent', result.data)
          break
        case 401:
          throw new Error('something wrong!')
        case 500:
          throw new Error('伺服器錯誤！')
        default:
          throw new Error("Oops! Something's wrong")
      }
    },
    async logout () {
      try {
        await axios.get('/auth/logout')
        return true
      } catch (error) {
        switch (error.status) {
          case 401:
            return true
          case 500:
            return false
          default:
            return false
        }
      }
    },
    async authentication (state, dispatch) {
      try {
        let result = await axios.get('/auth/authentication')
        return {status: true, data: result.data}
      } catch (error) {
        if (error.status === 401) {
          return {status: false}
        }
      }
    }
  },
  getters: {
    checkPermission (state, getters, rootState, rootGetters) {
      return (module, functionItem) => {
        const permission = state.current.permissions.reduce((map, obj) => ({
          ...map,
          [obj.name]: obj.functionItem
        }), {})
        let obj = permission[module].find(item => item.englishName === functionItem)
        return obj.permission
      }
    }
  }
}
