import Vue from 'vue'
import Vuex from 'vuex'
import cache from '@/plugins/cache'

Vue.use(Vuex)

const store = new Vuex.Store({
  getters: {
    // 获取用户信息
    userinfo(state) {
      if (store._vm._.isEmpty(state.userinfo)) {
        store._vm.$toast('请先登录')
        store.commit('removeUserInfo')
        return uni.reLaunch({ url: '/pages/index/index' })
      }
      return state.userinfo
    },
    // 获取位置信息
    location: state => state.location,
  },
  state: {
    // 订单备注
    ordersRemark: '',
    // 地址信息
    address: {},
    // 当前定位
    location: {},
    token: '',
    network: 'wifi',
    connected: true,
    apiError: null,
    WXcode: {},
    userinfo: cache.get('userinfo', {}),
  },
  mutations: {
    // 缓存订单备注
    setOrdersRemark(state, value) {
      state.ordersRemark = value
    },
    delOrdersRemark(state) {
      state.ordersRemark = ''
    },
    // 获取地址
    setAddress(state, data) {
      state.address = data
    },
    delAddress(state) {
      state.address = {}
    },
    // 缓存当前定位
    setLocation(state, data) {
      state.location = data
    },
    getToken(state, value) {
      state.token = value
    },
    // 设置网络类型和连接状态
    setNetwork(state, payload) {
      state.network = payload.type
      state.connected = payload.status
    },
    // 设置 API 错误状态
    setApiError(state, status) {
      state.apiError = status
    },
    // 登录信息
    setWXcode(state, data) {
      state.WXcode = data
    },
    // 设置用户信息
    setUserInfo(state, info) {
      state.userinfo = { ...state.userinfo, ...info }
      cache.set('userinfo', state.userinfo)
    },
    // 清除用户信息
    removeUserInfo(state) {
      state.userinfo = {}
      cache.remove('token')
      cache.remove('userinfo')
    },
  },
  actions: {},
})

export default store
