import { getUser, logout } from '@/api'

export const state = () => ({
  user: {},
  searchVisible: false,
  menuVisible: false,
  locales: ['zh-CN', 'en-US'],
  locale: 'zh-CN'
})

export const mutations = {
  setUser(state, user) {
    state.user = user
  },
  toggleSearch(state, visible) {
    state.searchVisible = visible
  },
  toggleMenu(state, visible) {
    state.menuVisible = visible
  },
  setLocale(state, locale) {
    if (state.locales.includes(locale)) {
      state.locale = locale
    }
  }
}

export const actions = {
  getUser({ commit }) {
    getUser().then(response => {
      commit('setUser', response.data)
    })
  },
  // 退出登录
  logout({ commit }) {
    logout().then(response => {
      commit('setUser', {})
      this.$router.replace('/')
    })
  },
  // 检测登录状态
  async checkLogin({ commit }) {
    console.log('000')
    const isLogin = await getUser()
      .then(response => {
        commit('setUser', response.data)
        return true
      })
      .catch(() => {
        commit('setUser', {})
        return false
      })
    return isLogin
  },
  switchLocale({ commit }, locale) {
    commit('setLocale', locale)
    this.app.i18n.locale = locale
    this.$cookies.set('lang', locale, { domain: 'ezijing.com' })
  }
}
