import Vue from 'vue'
import Vuex from 'vuex'
import preState from 'vuex-persistedstate'
import request from '@/api'
import router from '@/router'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    mallId: '',
    mallName: '',
    mallList: [],
    activeDlgShow: false,
    userInfo: {}
  },

  mutations: {
    setToken(state, token) {
      state.token = token
    },
    setMallId(state, mallId) {
      state.mallId = mallId
    },
    setMallName(state, mallName) {
      state.mallName = mallName
    },
    setMallList(state, mallList) {
      state.mallList = mallList
    },
    logout(state) {
      state.token = ''
      state.userInfo = {}
      state.mallList = []
      state.mallName = ''
      state.mallId = ''

      setTimeout(() => {
        router.push('/login')
      }, 200)
    },

    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setActiveDlgShow(state, flag) {
      state.activeDlgShow = flag
    }
  },

  actions: {
    getUserInfo(store) {
      return new Promise(resolve => {
        request.post('/api/malluser/info').then(res => {
          if (res.code === 0) {
            store.commit('setUserInfo', res.data)
            resolve(res.data)
          }
        })
      })
    },
    SignOut(store, isClear) {
      if (isClear) {
        store.commit('logout')
        return false
      }

      request.post('/api/token/logout').then(res => {
        if (res.code === 0) {
          store.commit('logout')
        }
      })
    }
  },

  getters: {
    isLogin: state => {
      return !!state.token
    }
  },

  plugins: [preState()]
})
