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

import { getUser, logout, getIsVip, createGuestUser } from '@/api/account'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {},
    token: '',
    isVip: false,
    isLogin: false,
    isIos: /iphone|ipad|ipod/i.test(navigator.userAgent),
    isAndroid: /android/i.test(navigator.userAgent),
    isWeapp: /miniProgram/.test(navigator.userAgent),
    guestUser: { user_id: '', student_id: '' }
  },
  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
    },
    setGuestUser(state, user) {
      state.guestUser = user
      window.localStorage.setItem('guestUser', JSON.stringify(user))
    }
  },
  actions: {
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    // 退出登录
    logout({ commit }) {
      return logout().then(response => {
        commit('setUser', {})
        commit('setIsLogin', false)
        return 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
    },
    // 检测是否付费
    async checkIsVip({ commit, state }) {
      if (!state.isVip) {
        await getIsVip().then(response => commit('setIsVip', response.is_vip))
      }
      return state.isVip
    },
    // 创建游客用户
    async createGuestUser({ commit, state }) {
      const { user_id: userId, student_id: studentId } = state.guestUser
      if (!userId || !studentId) {
        await createGuestUser().then(response => commit('setGuestUser', response))
      }
      return state.guestUser
    },
    // 加载本地游客信息
    loadGuestUser({ commit, state }) {
      const localGuestUser = window.localStorage.getItem('guestUser')
      let guestUser = { user_id: '', student_id: '' }
      if (localGuestUser) {
        try {
          guestUser = JSON.parse(localGuestUser)
        } catch (error) {
          console.log(error)
        }
      }
      commit('setGuestUser', guestUser)
    }
  }
})

export default store

// 加载本地游客用户
// store.dispatch('loadGuestUser')
// 检测是否付费
// store.dispatch('checkIsVip')
