import Vue from 'vue'
import Vuex from 'vuex'
import { getUser } from '@/api/account'
import { getVoteList } from '@/api/vote'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    groupList: [],
    user: {},
    voteList: []
  },
  mutations: {
    setGroupList(state, list) {
      state.groupList = list
    },
    setUser(state, user) {
      state.user = user
    },
    setVoteList(state, list) {
      state.voteList = list
    }
  },
  actions: {
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    async checkLogin({ commit }) {
      const isLogin = await getUser()
        .then(response => {
          if (response.code === 0) {
            commit('setUser', response.data)
            return true
          } else {
            commit('setUser', {})
            return false
          }
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      return isLogin
    },
    async getVoteList({ commit }, city) {
      await getVoteList({ city }).then(response => {
        response = response.map(item => {
          item.collapsed = false
          item.limit = item.limit ? parseInt(item.limit) : 0
          item.checkedCount = 0
          item.candidate = item.candidate.map(user => {
            user.checked = false
            return user
          })
          return item
        })
        commit('setVoteList', response)
      })
    }
  }
})
