import { login, getInfo, logout } from '~/api/user'
import { getToken, setToken, removeToken } from '~/assets/scripts/auth'

const user = {
  state: {
    token: getToken(),
    userInfo: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.userInfo = user
    },
    SET_UNREAD: (state, user) => {
      state.unRead = user
    }
  },

  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          setUserInfo(res.user, commit)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          setUserInfo(res.data, commit)
          commit('SET_USER', res.data)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  removeToken()
}

export const setUserInfo = (res, commit) => {
  commit('SET_USER', res)
}

export default user
