export default {
  state: {
    user: {},
    token: '',
    session: '',
    kid: 0,
    phone: '',
    carts: []// 购物车
  },
  getters: {
    user(state) {
      return state.user.nickName ? state.user : JSON.parse(uni.getStorageSync('user'))
    },
    kid(state) {
      return state.kid || uni.getStorageSync('kid')
    },
    phone(state) {
      return state.phone || uni.getStorageSync('phone')
    },
    token(state) {
      return state.token || uni.getStorageSync('token')
    },
    session(state) {
      return state.session || uni.getStorageSync('session')
    },
    carts(state) {
      return state.carts.length > 0 ? state.carts : JSON.parse(uni.getStorageSync('carts'))
    }
  },
  mutations: {
    CLEAR(state) {
      state.user = {}
      state.token = ''
      state.session = ''
      state.phone = ''
      state.kid = 0
      state.carts = []
      uni.clearStorageSync()
    },
    SET_USER(state, user = {}) {
      state.user = user
      uni.setStorage({
        key: 'user',
        data: JSON.stringify(user)
      })
    },
    SET_PHONE(state, phone) {
      state.phone = phone
      uni.setStorage({
        key: 'phone',
        data: phone
      })
    },
    SET_KID(state, kid) {
      state.kid = kid
      uni.setStorage({
        key: 'kid',
        data: kid
      })
    },
    SET_TOKEN(state, token) {
      state.token = token
      uni.setStorage({
        key: 'token',
        data: token
      })
    },
    SET_SESSION(state, session) {
      state.session = session
      uni.setStorage({
        key: 'session',
        data: session
      })
    },
    SET_CARTS(state, carts = []) {
      state.carts = carts
      uni.setStorage({
        key: 'carts',
        data: JSON.stringify(carts)
      })
    }
  },
  actions: {
    clear({ commit }) {
      return new Promise((resolve, reject) => {
        commit('CLEAR')
        resolve(true)
      })
    },
    setUser({ commit }, user) {
      commit('SET_USER', user)
    },
    setPhone({ commit }, phone) {
      commit('SET_PHONE', phone)
    },
    setKid({ commit }, kid) {
      return new Promise((resolve, reject) => {
        commit('SET_KID', kid)
        resolve(kid)
      })
    },
    setToken({ commit }, token) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', token)
        resolve(token)
      })
    },
    setSession({ commit }, session) {
      commit('SET_SESSION', session)
    },
    setCarts({ commit }, carts) {
      commit('SET_CARTS', carts)
    }
  }
}
