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

import { getUser, logout, getIsVip } from '@/api/account'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    user: {},
    token: '',
    isVip: false,
    isLogin: false,
    isWeapp: /miniProgram/.test(navigator.userAgent)
  },
  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
    },
    setIsVip(state, isVip) {
      state.isVip = isVip
    }
  },
  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
      })
    },
    async checkIsVip({ commit, state }) {
      if (state.isVip) {
        return state.isVip
      }
      const isVip = await getIsVip()
        .then(response => response.is_vip)
        .catch(() => false)
      commit('setIsVip', isVip)
      return isVip
    }
  }
})
