import i18n from '../i18n'; import request from '../Utils/RequestUtils'; import { addAsyncStorage, removeAsyncStorage, } from '../Utils/AsyncStorageUtils'; import submitPhone from '../Utils/FormUtils'; import Toast from './Toast'; import { alert } from '../Utils/TotastUtils'; const app = (now) => ({ id: null, userInfo: {}, getUser() { return request .get('/user/my') .then((res) => { now({ id: res.id, userInfo: res, }); }) .catch((e) => { now({ id: 0, }); return Promise.reject(e); }); }, loginByPsd(phone, password) { const { loading, warnning, success } = now(Toast); loading(); return request .post('/auth/loginByRegister', { data: { phone: submitPhone(phone), password, identity: 'USER', }, requestType: 'form', }) .then((res) => { return addAsyncStorage('token', res); }) .then(() => { const { getUser } = now(); return getUser(); }) .then(() => { success(i18n.t('deng-lu-cheng-gong')); }) .catch((e) => { warnning(e.error); }); }, loginByCode(phone, code) { const { loading, warnning, success } = now(Toast); loading(); return request .post('/auth/phoneLogin', { data: { phone: `+86${submitPhone(phone)}`, code, identity: 'USER', }, requestType: 'form', }) .then((res) => { return addAsyncStorage('token', res); }) .then(() => { const { getUser } = now(); return getUser(); }) .then(() => { success(i18n.t('deng-lu-cheng-gong')); }) .catch((e) => { warnning(e.error); }); }, logout() { alert('', `${i18n.t('que-ding-yao-tui-chu-gai-zhang-hao-ma')}?`, () => { const { loading, success } = now(Toast); loading(); // 移除 token removeAsyncStorage('token').then(() => { // 清除用户信息 now({ id: 0, userInfo: {} }); success(i18n.t('tui-chu-cheng-gong')); }); }); }, uploadInfo({ ...info }) { const { id, getUser } = now(); const { loading, warnning, success } = now(Toast); loading(); return request .post('/user/save', { data: { ...info, id, }, }) .then(() => { return getUser(); }) .then(() => { success(i18n.t('geng-xin-cheng-gong')); return Promise.resolve(); }) .catch((e) => { warnning(e.error); }); }, loginByRegister(phone, password) { const { loading, warnning, success } = now(Toast); loading(); return request .post('/auth/loginByRegister', { data: { phone: submitPhone(phone), password, }, requestType: 'form', }) .then(() => { return request.post('/auth/login', { data: { username: submitPhone(phone), password, }, requestType: 'form', }); }) .then((res) => { return addAsyncStorage('token', res); }) .then(() => { const { getUser } = now(); return getUser(); }) .then(() => { success(i18n.t('zhu-ce-cheng-gong')); }) .catch((e) => { warnning(e.error); }); }, }); export default app;