/**
 * @Description: 用户模块
 * @Author: 空白格
 * @Date: 2022-08-10 13:40:53
 * @LastEditors: 空白格
 * @LastEditTime: 2022-08-25 15:11:48
 * @FilePath: \veterans_client_web\src\store\modules\user.js
 * @Copyright: Copyright (c) 2016~2022 by 空白格, All Rights Reserved.
 */
import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAuthCode, getAuthCode, getUserInfo, logout } from '@/api/Login'
const user = {
  state: {
    token: getToken(),
    isLogin: false,
    userInfo: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_LOGIN_FLAG: (state, flag) => {
      state.isLogin = flag
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 验证登录验证码
    Login({ commit, state }, userInfo) {
      console.log(state)
      return new Promise((resolve, reject) => {
        loginAuthCode({
          accessToken: state.token,
          userId: userInfo.userId,
          code: userInfo.code
        })
          .then((res) => {
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取登录验证码
    GetLoginCode({ commit }, param) {
      return new Promise((resolve, reject) => {
        getAuthCode(param)
          .then((res) => {
            commit('SET_TOKEN', res.data.accessToken)
            setToken(res.data.accessToken)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            commit('SET_LOGIN_FLAG', true)
            commit('SET_USER_INFO', res.data)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出登录
    Logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout({})
          .then((res) => {
            commit('SET_LOGIN_FLAG', false)
            commit('SET_USER_INFO', {})
            commit('SET_TOKEN', '')
            removeToken()
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}
export default user
