import Vue from 'vue'
import Vuex from 'vuex'
import Cookies from 'js-cookie'

import { getUser, logout } 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) {
        commit('setIsWeapp', res.miniprogram)
      })
    },
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    async checkLogin({ commit }) {
      const isLogin = await getUser()
        .then(response => {
          commit('setUser', response)
          commit('setToken', Cookies.get('TGC'))
          return true
        })
        .catch(() => {
          commit('setUser', {})
          commit('setToken', '')
          return false
        })
      commit('setIsLogin', isLogin)
      return isLogin
    },
    logout({ commit }) {
      return logout().then(response => {
        commit('setUser', {})
        commit('setIsLogin', false)
        return response
      })
    }
  }
})
