import { login, logout, resetPassword } from '@/api/user'
import { getToken, setToken, removeToken, setName, setUserId, setUserAvatar } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => ({
  token: getToken(),
  name: '',
  avatar: ''
})

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, rememberMe } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, code, rememberMe }).then((response) => {
        const { data } = response
        // debugger;
        setName(data.name)
        setUserId(data.platformUserId)
        setUserAvatar(data.avatar)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
        commit('SET_LOAD', true)
        resolve()
        // 切换账号,刷新路由
        location.reload()
      })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        // 路由重置
        resetRouter()
        commit('SET_LOAD', false)
        // -
        commit('RESET_STATE')
        resolve()
      })
        .catch((error) => {
          reject(error)
        })
    })
  },

  resetPassword({ commit }, authForm) {
    const { phone, password, newPassword, code } = authForm
    return new Promise((resolve, reject) => {
      resetPassword({ username: phone.trim(), password, newPassword, code }).then((response) => {
        resolve()
      })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

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

