import type { IStationInfo, IUser } from '@/types/user' import { defineStore } from 'pinia' import { store } from '@/store' interface UserState { user: null | IUser // 用户信息 stationInfo: null | IStationInfo // 检测站信息 } export const useUserStore = defineStore({ id: 'user', state: (): UserState => ({ user: null, stationInfo: null, }), getters: { // 用户姓名 getUserRealName: ({ user }) => user?.xm || '', // 检测站编号 getStationNo: ({ user }) => user?.jczbh || '', // 身份证号码 getIdCard: ({ user }) => user?.sfzmhm || '', // 获取检测站名称 getStationName: ({ stationInfo }) => stationInfo?.jczmc || '', }, actions: { // 登录 async login(query) { try { const res = await uni.$u.api.login(query) if (res?.length) { uni.setStorageSync('user', JSON.stringify(res[0])) this.user = res[0] uni.$u.toast('登录成功') this.getStationInfo(this.user!.jczbh) setTimeout(() => { uni.switchTab({ url: '/pages/index/index' }) }, 1500) return } uni.removeStorageSync('user') this.user = null } catch (error: any) { this.user = null uni.removeStorageSync('user') } }, // 获取检测站信息 async getStationInfo(stationNo: string) { try { const res = await uni.$u.api.getStationInfo(stationNo) this.stationInfo = res?.length ? res[0] : null if (res?.length) { this.stationInfo = res[0] uni.setStorageSync('station', JSON.stringify(this.stationInfo)) } else { uni.removeStorageSync('station') } } catch (error: any) { this.stationInfo = null uni.removeStorageSync('station') } }, setUser(data) { this.user = data || null }, }, }) // Need to be used outside the setup export function useUserStoreWidthOut() { return useUserStore(store) }