import { login, logout } from '@/api/user/auth'
import { register } from '@/api/user/account'
import { getMyInfo } from '@/api/user/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    userInfo: null,
    token: getToken(),
    name: '',
    roles: [],
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_VIP: (state, vipInfo) => {
    state.userInfo.vip = vipInfo.vip
    state.userInfo.expiredAt = vipInfo.expiredAt
  }
}

const actions = {
  // 用户注册
  register({ commit }, registerData) {
    return new Promise((resolve, reject) => {
      register(registerData).then(res => {
        if (res.code === 0) {
          resolve()
        } else {
          alert(res.data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 用户登录
  login({ commit }, loginData) {
    return new Promise((resolve, reject) => {
      login(loginData).then(res => {
        if (res.code === 0) {
          const token = res.data.token
          commit('SET_TOKEN', token)
          setToken(token)

          getMyInfo().then(res => {
            if (res.code === 0) {
              const userInfo = res.data
              commit('SET_USER_INFO', userInfo)
              resolve()
            } else {
              console.log(res.data)
            }
          }).catch(error => {
            reject(error)
          })
        } else {
          console.log(res.data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      resolve()
    })
  },
  // 用户注销
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
        console.log('注销错误 -> ')
        console.log(error)
      })
    })
  },
  // 删除本地存储的 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
