suke-mp/src/store/modules/user/index.ts
2024-06-06 11:49:38 +08:00

208 lines
6.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { defineStore } from 'pinia';
import type { providerType, UserBean } from './types';
import { getTerminal, getUserProfile, login, logout as userLogout, register } from '@/api/user/index';
import {
clearToken,
getCompanyId,
getRegisterStoreId,
setCompanyId,
setOpenId,
setSessionKey,
setToken
} from '@/utils/auth';
import type { RegisterParams, TerminalBean } from '@/api/user/types';
import { getCompanyInfo } from '@/api/company';
const useUserStore = defineStore('user', {
state: () => ({
userInfo: {} as UserBean,
terminalInfo: {} as TerminalBean,
companyInfo: {} as any,
companyConfigInfo: {
bannerhot: [] as any[],
bannerinx: [] as any[],
goodsdisable: 0,
goodsstockzero: 0,
mallopen: 0,
regqrcode: undefined,
userbgcover: undefined,
groupqrcode: undefined,
contactname: '',
contacttelephone: ''
},
deliveryAddress: {
addrid: '',
name: '',
mobile: '',
addr: '',
defaultstatus: 0
}
}),
persist: {
// 修改存储中使用的键名称,默认为当前 Store的 id
key: 'userState',
storage: {
setItem(key, value) {
uni.setStorageSync(key, value); // [!code warning]
},
getItem(key) {
return uni.getStorageSync(key); // [!code warning]
}
},
// 部分持久化状态的点符号路径数组,[]意味着没有状态被持久化(默认为undefined持久化整个状态)
paths: undefined
},
getters: {
getUserDiscount(): number {
if(this.userInfo?.levelEntity?.discount > 0 && this.userInfo?.levelEntity?.discount < 10) {
return this.userInfo?.levelEntity?.discount / 10;
} else if(this.userInfo?.levelEntity?.discount >= 10 && this.userInfo?.levelEntity?.discount <= 100) {
return this.userInfo?.levelEntity?.discount / 100;
}
return 1;
},
getRealGoodsPrice: (state) => (price: number, priceExt: number) => {
return state.userInfo.salePrice == 'price_ext' ? priceExt || 0 : price;
}
},
actions: {
login(provider: providerType = 'weixin') {
return new Promise((resolve, reject) => {
uni.login({
provider,
success: async (result: UniApp.LoginRes) => {
if(result.code) {
const wechatUserInfo = await uni.getUserInfo();
const userInfo = {
...wechatUserInfo.userInfo,
encryptedData: wechatUserInfo?.encryptedData,
rawData: JSON.parse(wechatUserInfo?.rawData),
signature: wechatUserInfo?.signature,
iv: wechatUserInfo.iv
};
getApp().globalData?.logger.info('login params: ', userInfo);
const res = await login({
code: result.code,
userInfo: userInfo,
storeId: getRegisterStoreId()
// referrerUserId: '1727303781559697409'
// referrerUserId: getReferrerUserId()
});
getApp().globalData?.logger.info('login result: ', res);
console.log('login result: ', res);
console.log('login result: ', res.token);
console.log('login result: ', res.sessionKey);
setToken(res.token);
setSessionKey(res.sessionKey);
setOpenId(res.maOpenId);
if(res.user) {
this.setUserInfo(res.user);
} else {
this.setUserInfo(res.userInfo);
}
// }
resolve(res);
} else {
getApp().globalData?.logger.error('login error: ', result.errMsg);
reject(new Error(result.errMsg));
}
},
fail: (err: any) => {
console.error(`login error: ${err}`);
getApp().globalData?.logger.error('login error: ', err);
reject(err);
}
});
});
},
register(params: {
image: string,
avatarUrl: string,
nickName: string,
telephone: string,
birthday: string,
gender: string
}) {
const registerForm = {
...params,
unionId: this.userInfo.unionId,
openId: this.userInfo.openId,
maOpenId: this.userInfo.maOpenId,
companyId: getCompanyId(),
creatorId: this.userInfo.creatorId,
storeId: getRegisterStoreId()
} as RegisterParams;
return new Promise(async (resolve, reject) => {
try {
const result = await register(registerForm);
resolve(result);
} catch (error) {
reject(error);
}
});
},
// 设置用户的信息
async setUserInfo(partial: Partial<UserBean>) {
this.userInfo = partial as UserBean;
// this.userInfo.levelEntity?.discount = 79;
// this.userInfo.salePrice = 'price_ext';
if(this.userInfo) {
this.userInfo.userDiscount = this.getUserDiscount;
await setCompanyId(this.userInfo.companyId);
if(getApp().globalData){
getApp().globalData.companyId = this.userInfo.companyId;
}
} else {
await clearToken();
}
this.fetchTerminal();
this.fetchCompanyInfo();
},
setCompanyInfo(partial: Partial<any>) {
this.companyInfo = partial as any;
if(getApp()?.globalData) {
getApp().globalData.companyId = this.companyInfo.id;
}
},
setDeliveryAddress(partial: Partial<any>) {
this.deliveryAddress = partial as any;
},
// 获取用户信息
async getProfile() {
const result = await getUserProfile();
await this.setUserInfo(result);
},
async fetchCompanyInfo() {
this.companyConfigInfo = await getCompanyInfo();
},
async fetchTerminal() {
this.terminalInfo = await getTerminal(this.userInfo?.companyId);
},
// 重置用户信息
resetInfo() {
this.$reset();
},
// Logout
async logout() {
await userLogout();
this.resetInfo();
clearToken();
}
}
});
export default useUserStore;