import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/utils/request'
import user from './modules/user'
import storage from '../utils/storage'

Vue.use(Vuex)

let userInfo = null
try {
  if (uni.getStorageSync('userInfo')) {
    userInfo = JSON.parse(userInfo)
  }
} catch (e) {
  uni.setStorageSync('userInfo', null)
}

const store = new Vuex.Store({
  state: {
    userInfo: userInfo || null,
    mobile: uni.getStorageSync('mobile'),
    config: null
  },
  mutations: {
    logout(state) {
      console.log('logout')
      state.userInfo = null
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
      uni.removeStorageSync('mobile')
      storage.clean()
      // uni.switchTab({
      // 	url: '/pages/tabbar/user/user.vue'
      // })
    },
    setUser(state, userInfo) {
      state.userInfo = userInfo
      console.log('userInfo.data', userInfo)
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
      uni.setStorageSync('mobile', userInfo.mobile)
      console.log('mobile', uni.getStorageSync('mobile'))
      uni.setStorageSync('token', userInfo.api_token)
    },
    setConfig(state, config) {
      state.config = config
    }
  },
  actions: {
    updateUserInfo({ commit }) {
      http
        .get('/app-api/member/user/get')
        .then((res) => {
          console.log('更新用户信息', res)
          commit('setUser', res.data)
        })
        .catch((res) => {
          console.log('更新用户信息error', res)
        })
    }
  },
  getters: {
    id: (state) => state.user.id,
    areaCode: (state) => state.user.areaCode,
    mobile: (state) => state.mobile
  },
  modules: {
    user
  }
})
export default store
