import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import user from './user'
import file from './file'
import staff from './staff'
import project from './project'
// eslint-disable-next-line camelcase
import paramsSetting from './paramsSetting'
import officialDocument from './officialDocument'
import newDocument from './newDocument'
import conference from './conference'
import issue from './issue'
import documentCollaboration from './documentCollaboration'
import schedule from './schedule'
import tenders from './tenders'
import supervision from './supervision'

Vue.use(Vuex)

// 定義一個新的 Vue Store
const store = new Vuex.Store({
  state: {
    enums: {},
    httpError: ''
  },
  getters: {
    getEnumWord (state) { // Enum轉換
      return (wordSet, wordEnum) => {
        if (wordEnum === undefined) return
        return Object.values(state.enums[wordSet]).map(item => { return {text: item.word, value: item.word} })
      }
    }
  },
  mutations: {
    setEnums (state, enums) {
      state.enums = enums
    },
    setHttpError (state, httpError) {
      state.httpError = httpError
    }
  },
  actions: {
    async getEnums ({commit}) { // 拿取enum
      let result = await axios.get('/enum')
      commit('setEnums', result.data)
    }
  },
  modules: {
    user: user,
    file: file,
    staff: staff,
    project: project,
    paramsSetting: paramsSetting,
    officialDocument: officialDocument,
    newDocument: newDocument,
    conference: conference,
    issue: issue,
    documentCollaboration: documentCollaboration,
    schedule: schedule,
    tenders: tenders,
    supervision: supervision
  }
})

axios.defaults.withCredentials = true
axios.defaults.baseURL = process.env.API_ROOT_URL
axios.interceptors.response.use(response => { return response },
  (error) => {
    console.error(error)
    // if (error.message === 'Network Error') alert('後端伺服器連線錯誤！')
    // if (error.response.status === 500) alert(`後端伺服器錯誤！\nAPI：${error.response.config.method} ${error.response.config.url}\n時間：${new Date().toLocaleString()}\n原因：${error.response.data}`)
    store.commit('setHttpError', error.toJSON(), {root: true})
    return Promise.reject(error.response)
  })

export default store
