import Vue from 'vue'
import Vuex from 'vuex'
import { getUser } from '@/api/account'
Vue.use(Vuex)
const UA = navigator.userAgent.toLowerCase()
export default new Vuex.Store({
  state: {
    isWeapp: /miniProgram/.test(UA),
    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
    }
  }
})
