import { message } from 'antd' import router from '../router/index.tsx' import http from './index' import { userLogin, sendVerificationCode, loginPhone, userLogout, changePassword, forgotPassword } from './api.ts' export function getAccessToken(): string { const accessToken = localStorage.getItem('token') return accessToken || '' } export function setAccessToken(token: string): void { localStorage.removeItem('token') localStorage.setItem('token', token) } export function clearAccessToken() { localStorage.removeItem('token') } type loginType = { token: string, isAdmin: boolean, menus: string[] } export function login(account: string, password: string) { return http.post(userLogin, { account, password }).then(res => { const { code, msg, data = {} } = res const { token, } = data as loginType if (code === 0) { message.success('登录成功') setAccessToken(token) return true } message.error(msg) return false }).catch(() => {}) } export function sendCode(phone: string) { return http.post(sendVerificationCode, { phone }).then(res => { const { code, msg = '发送失败' } = res if (code === 0) { message.success('短信已发送,请注意查收') return true } message.error(msg) return false }).catch(() => {}) } export function loginBySendCode(phone: string, verificationCode: string) { return http.post(loginPhone, { phone, verificationCode }).then(res => { const { code, msg, data = {} } = res const { token } = data as loginType if (code === 0) { message.success('登录成功') setAccessToken(token) return true } message.error(msg) return false }).catch(() => {}) } export function logout() { return http.post(userLogout).then(res => { const { code, msg } = res if (code === 0) { message.success('退出登录成功') clearAccessToken() router.navigate('/login') return true } message.error(msg) return false }).catch(() => {}) } export function changeLoginPassword(oldPassword: string, newPassword: string) { return http.post(changePassword, { oldPassword, newPassword }).then(res => { const { code, msg } = res if (code === 0) { message.success('修改密码成功') clearAccessToken() router.navigate('/login') return true } message.error(msg) return false }).catch(() => {}) } export function forgotLoginPassword(phone: string, verificationCode: string, newPassword: string) { return http.post(forgotPassword, { phone, verificationCode, newPassword }).then(res => { const { code, msg } = res if (code === 0) { message.success('密码编辑成功') clearAccessToken() return true } message.error(msg) return false }).catch(() => {}) } export default { getAccessToken, setAccessToken, clearAccessToken, login, sendCode, loginBySendCode, logout, changeLoginPassword, forgotLoginPassword, }