import {
  login,
  logout,
} from '../../api/userAction'

import { setToken, getToken,getLocalUserMap,getRegisterUserMap,handleUserInfo} from '../../libs/cookieUtil'

export default {
  state: {
    userName: '',
    userId: '',
    token: getToken(),
  },
  mutations: {
    setUserName (state, name) {
      state.userName = name
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
  },
  getters: {
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password}) {
      const localUserInfo = handleUserInfo()
      console.log(localUserInfo)
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          localUserInfo
        }).then(res => {
          console.log("actions handleLogin")
          console.log(res)
          commit('setToken', res.token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
  }
}
