/*
 * @Description: 
 * @Author: 欧阳承珺
 * @LastEditors: 欧阳承珺
 * @Date: 2022-10-25 17:19:19
 * @LastEditTime: 2022-11-16 13:51:41
 */
import { setToken, cookieParse } from '~/utils/cookie'

export const state = () => ({
  userInfo: {},
  token: '',
  globalLoginVisiable: false,
  globalInterfaceType: false
})

export const mutations = {
  setUser(state, data) {
    state.userInfo = data
  },
  SET_TOKEN(state, data) {
    state.token = data
  },
  DEL_TOKEN(state,data) {
    state.token = data
  },
  OPEN_LOGIN(state, data) {
    state.globalLoginVisiable = data
  },
  SET_INTERFACE(state, data) {
    state.globalInterfaceType = data
  }
}


export const actions = {

  nuxtServerInit ({commit, state}, {req}) {
    let token = null
    let userInfo = null
    if (req && req.headers && req.headers.cookie) {
      const parsed = cookieParse(req.headers.cookie)
      try {
        token = parsed?.Token || ''
        userInfo = JSON.parse(decodeURIComponent(parsed.vuex)).userInfo
      } catch (err) {
      }
      commit('SET_TOKEN', token)
      commit('setUser', userInfo)
    }
  },

  login ({ commit }, params) {
    return new Promise((resolve, reject) => {
      this.$axios.get(`auth/getToken?code=${params}`).then(res => {
        const token = res.result.accessToken
        setToken('Token', token)
        localStorage.setItem('token',token)
        commit('SET_TOKEN', token)
        resolve(token)
      }).catch(err => {
        reject(err)
      })
    })
  },
} 