import Vue from 'vue'
import Vuex from 'vuex'
import { getUser } from '@/api/account'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    isWeapp: /miniProgram/.test(navigator.userAgent),
    isLogin: false,
    token: '',
    user: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    setUser(state, user) {
      state.user = user
    },
    setIsWeapp(state, isWeapp) {
      state.isWeapp = isWeapp
    },
    setIsLogin(state, isLogin) {
      state.isLogin = isLogin
    }
  },
  actions: {
    getEnv({ commit }) {
      wx.miniProgram.getEnv(function(res) {
        console.log(res.miniprogram) // true
        commit('setIsWeapp', res.miniprogram)
      })
    },
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    async checkLogin({ commit }) {
      const isLogin = await getUser()
        .then(response => {
          commit('setUser', response)
          return true
        })
        .catch(() => {
          return false
        })
      commit('setIsLogin', isLogin)
      return isLogin
    }
  }
})
