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

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

export const mutations = {
  setLearning() {
    state.learning = learning
  },
  setUser(state, user) {
    state.user = user
  },
  removeUser(state) {
    state.user = {}
  },
  setIsMobile(state, isMobile) {
    state.isMobile = isMobile
  },
  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)
      commit('setLearning', response.data.learning_info)
      this.$store.commit('setUserId', item.id)
    })
  },
  // 退出登录
  logout({ commit }) {
    logout().then(response => {
      commit('setUser', {})
    })
  },
  // 检测登录状态
  async checkLogin({ commit }) {
    console.log('000')
    const isLogin = await getUser()
      .then(response => {
        commit('setUser', response.data)
        console.log(response.data.learning_info, 'data')
        window.localStorage.setItem('learningList', JSON.stringify(response.data.learning_info))
        console.log(JSON.parse(window.localStorage.getItem('learningList')))
        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' })
  }
}
