This commit is contained in:
张成
2025-09-10 21:43:36 +08:00
parent d38baa9c5b
commit 5fdee20d45
12 changed files with 281 additions and 152 deletions

View File

@@ -3,7 +3,6 @@ import './nutui-theme.scss'
import './app.scss'
import { useDictionaryStore } from './store/dictionaryStore'
import { useGlobalStore } from './store/global'
import { check_login_status } from './services/loginService';
// import { getNavbarHeight } from "@/utils/getNavbarHeight";

View File

@@ -1,6 +1,5 @@
import React, { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { check_login_status } from '@/services/loginService'

View File

@@ -17,15 +17,14 @@ const envConfigs: Record<EnvType, EnvConfig> = {
// 开发环境
development: {
name: '开发环境',
apiBaseURL: 'https://sit.light120.com',
// apiBaseURL: 'http://localhost:9098',
//apiBaseURL: 'https://sit.light120.com',
apiBaseURL: 'http://localhost:9098',
timeout: 15000,
enableLog: true,
enableMock: true
},
// 生产环境
production: {
name: '生产环境',

View File

@@ -1,6 +1,8 @@
import { View, Text, Image } from "@tarojs/components";
import img from "@/config/images";
import { useGlobalState } from "@/store/global";
import { useUserInfo, } from '@/store/userStore'
import { useListState } from "@/store/listStore";
import CustomNavbar from "@/components/CustomNavbar";
import { Input } from "@nutui/nutui-react-taro";
@@ -32,9 +34,11 @@ const ListHeader = (props: IProps) => {
const { gamesNum, searchValue, isShowInputCustomerNavBar } = useListState();
const { statusBarHeight, navbarHeight } = statusNavbarHeightInfo;
const currentAddress = getLocationLoading
? getLocationText
: location?.address;
const { city,district } = useUserInfo()
console.log("useUserInfo",city,district )
const currentAddress = city + district
const handleInputClick = () => {
const pages = Taro.getCurrentPages();
@@ -69,9 +73,8 @@ const ListHeader = (props: IProps) => {
<View className="listNavWrapper">
{/* 首页logo 导航*/}
<View
className={`listNavContainer toggleElement firstElement hidden ${
(!isShowInputCustomerNavBar && !showInput) && "visible"
}`}
className={`listNavContainer toggleElement firstElement hidden ${(!isShowInputCustomerNavBar && !showInput) && "visible"
}`}
style={{
height: `${navbarHeight}px`,
paddingTop: `${statusBarHeight}px`,
@@ -94,16 +97,15 @@ const ListHeader = (props: IProps) => {
)}
</View>
<View className="listNavInfoWrapper">
<Text className="listNavInfo">${gamesNum}</Text>
<Text className="listNavInfo">{gamesNum}</Text>
</View>
</View>
</View>
</View>
{/* 搜索导航 */}
<View
className={`inputCustomerNavbarContainer toggleElement secondElement hidden ${
(isShowInputCustomerNavBar || showInput) && "visible"
} ${showInput && "inputCustomerNavbarShowInput"}`}
className={`inputCustomerNavbarContainer toggleElement secondElement hidden ${(isShowInputCustomerNavBar || showInput) && "visible"
} ${showInput && "inputCustomerNavbarShowInput"}`}
style={{
height: `${navbarHeight}px`,
paddingTop: `${statusBarHeight}px`,

View File

@@ -642,7 +642,12 @@ function Index() {
try {
const location = await getCurrentLocation()
setCurrentLocation([location.latitude, location.longitude])
// 使用 userStore 中的统一位置更新方法
await updateUserInfo({ latitude: location.latitude, longitude: location.longitude })
// 位置更新后,重新获取详情页数据(因为距离等信息可能发生变化)
await fetchDetail()
} catch (error) {
console.error('用户位置更新失败', error)
}

View File

@@ -1,21 +1,40 @@
import React from 'react';
import React, { useEffect } from 'react';
import { View, } from '@tarojs/components';
import { check_login_status } from '../../services/loginService';
import { useUserActions } from '@/store/userStore';
import Taro from '@tarojs/taro';
const HomePage: React.FC = () => {
let login_status = check_login_status()
if (login_status) {
Taro.redirectTo({ url: '/pages/list/index' })
}
else {
Taro.redirectTo({ url: '/pages/login/index/index' })
}
const { fetchUserInfo } = useUserActions();
useEffect(() => {
const handleLoginRedirect = async () => {
const login_status = check_login_status();
if (login_status) {
try {
// 先获取用户信息
await fetchUserInfo();
// 用户信息获取成功后跳转到列表页
Taro.redirectTo({ url: '/pages/list/index' });
} catch (error) {
console.error('获取用户信息失败:', error);
// 如果获取用户信息失败,跳转到登录页
Taro.redirectTo({ url: '/pages/login/index/index' });
}
} else {
Taro.redirectTo({ url: '/pages/login/index/index' });
}
};
handleLoginRedirect();
}, [fetchUserInfo]);
return (
<View className="home_page">
</View>)
<View>...</View>
</View>
);
}
export default HomePage;

View File

@@ -11,6 +11,7 @@ import GuideBar from "@/components/GuideBar";
import ListContainer from "@/container/listContainer";
import DistanceQuickFilter from "@/components/DistanceQuickFilter";
import { withAuth } from "@/components";
import { updateUserLocation } from "@/services/userService";
// import img from "@/config/images";
// import ShareCardCanvas from "@/components/ShareCardCanvas/example";
@@ -66,16 +67,29 @@ const ListPage = () => {
useEffect(() => {
// 只有当 distanceQuickFilter 有值时才调用接口
if (distanceQuickFilter?.distance !== undefined || distanceQuickFilter?.quick !== undefined) {
console.log('距离或排序方式发生变化,重新获取数据:', distanceQuickFilter);
getMatchesData();
if (distanceQuickFilter?.quick !== "0") {
getMatchesData();
}
}
}, [distanceQuickFilter?.distance, distanceQuickFilter?.quick]);
// 获取位置信息
const getLocation = async () => {
const location = await getCurrentLocationInfo()
// 保存位置
// 保存位置到全局状态
updateState({ location });
// 同时更新用户位置到后端和 store
if (location && location.latitude && location.longitude) {
try {
await updateUserLocation(location.latitude, location.longitude);
} catch (error) {
console.error('更新用户位置失败:', error);
}
}
// 页面加载时获取数据
getMatchesData();
return location;

View File

@@ -1,6 +1,7 @@
import Taro from '@tarojs/taro';
import httpService, { ApiResponse } from './httpService';
import httpService from './httpService';
import tokenManager from '../utils/tokenManager';
import { useUser } from '@/store/userStore';
// 微信用户信息接口
export interface WechatUserInfo {
@@ -34,25 +35,12 @@ export interface VerifyCodeResponse {
token?: string;
user_info?: WechatUserInfo;
}
// 用户详细信息
export interface UserInfoType {
id: number
openid: string
unionid: string
session_key: string
nickname: string
avatar_url: string
gender: string
country: string
province: string
city: string
language: string
phone: string
is_subscribed: string
latitude: number
longitude: number
subscribe_time: string
last_login_time: string
// 手机号验证码登录接口参数
export interface PhoneLoginParams {
phone: string;
verification_code: string;
user_code: string
}
@@ -76,6 +64,13 @@ export const wechat_auth_login = async (phone_code?: string): Promise<LoginRespo
});
if (auth_response.code === 0) {
// 登录成功后,更新用户信息到 store
try {
await useUser.getState().fetchUserInfo();
} catch (error) {
console.error('更新用户信息到 store 失败:', error);
}
return {
success: true,
message: '微信登录成功',
@@ -116,6 +111,13 @@ export const phone_auth_login = async (params: PhoneLoginParams): Promise<LoginR
if (verify_response.code === 0) {
// 登录成功后,更新用户信息到 store
try {
await useUser.getState().fetchUserInfo();
} catch (error) {
console.error('更新用户信息到 store 失败:', error);
}
return {
success: true,
message: '登录成功',
@@ -276,19 +278,6 @@ export const get_token_status = () => {
}
};
// 获取用户信息
export const get_user_info = (): WechatUserInfo | null => {
try {
let userinfo = Taro.getStorageSync('user_info')
if (userinfo) {
return JSON.parse(userinfo)
}
return null;
} catch (error) {
return null;
}
};
// 获取用户token
export const get_user_token = (): string | null => {
try {
@@ -330,24 +319,9 @@ export const refresh_login_status = async (): Promise<boolean> => {
}
};
// 获取用户详细信息
export const fetchUserProfile = async (): Promise<ApiResponse<UserInfoType>> => {
try {
const response = await httpService.post('user/detail');
return response;
} catch (error) {
console.error('获取用户信息失败:', error);
throw error;
}
};
// 更新用户信息
export const updateUserProfile = async (payload: Partial<UserInfoType>) => {
try {
const response = await httpService.post('/user/update', payload);
return response;
} catch (error) {
console.error('更新用户信息失败:', error);
throw error;
}
};

View File

@@ -1,8 +1,8 @@
import { UserInfo } from '@/components/UserInfo';
import Taro from '@tarojs/taro';
import { API_CONFIG } from '@/config/api';
import httpService from './httpService';
import httpService, { ApiResponse } from './httpService';
import uploadFiles from './uploadFiles';
import Taro from '@tarojs/taro';
// 用户详情接口
@@ -35,55 +35,28 @@ interface UserDetailData {
};
}
// 更新用户信息参数接口
interface UpdateUserParams {
nickname: string;
avatar_url: string;
gender: string;
phone: string;
latitude?: string;
longitude?: string;
city: string;
province: string;
country: string;
// 用户详细信息接口(从 loginService 移过来)
export interface UserInfoType {
id: number
openid: string
unionid: string
session_key: string
nickname: string
avatar_url: string
gender: string
country: string
province: string
city: string
district:string
language: string
phone: string
is_subscribed: string
latitude: number
longitude: number
subscribe_time: string
last_login_time: string
}
// 上传响应接口
interface UploadResponseData {
create_time: string;
last_modify_time: string;
duration: string;
thumbnail_url: string;
view_count: string;
download_count: string;
is_delete: number;
id: number;
user_id: number;
resource_type: string;
file_name: string;
original_name: string;
file_path: string;
file_url: string;
file_size: number;
mime_type: string;
description: string;
tags: string;
is_public: string;
width: number;
height: number;
uploadInfo: {
success: boolean;
name: string;
path: string;
ossPath: string;
fileType: string;
fileSize: number;
originalName: string;
suffix: string;
storagePath: string;
};
}
// 后端球局数据接口
interface BackendGameData {
@@ -284,7 +257,7 @@ export class UserService {
}
}
// 更新用户信息
// 更新用户信息(简化版本,具体逻辑在 userStore 中处理)
static async update_user_info(update_data: Partial<UserInfo>): Promise<void> {
try {
// 过滤掉空字段
@@ -490,4 +463,55 @@ export class UserService {
return require('../static/userInfo/default_avatar.svg');
}
}
}
}
// 从 loginService 移过来的用户相关方法
// 获取用户详细信息
export const fetchUserProfile = async (): Promise<ApiResponse<UserInfoType>> => {
try {
const response = await httpService.post('user/detail');
return response;
} catch (error) {
console.error('获取用户信息失败:', error);
throw error;
}
};
// 更新用户信息
export const updateUserProfile = async (payload: Partial<UserInfoType>) => {
try {
const response = await httpService.post('/user/update', payload);
return response;
} catch (error) {
console.error('更新用户信息失败:', error);
throw error;
}
};
// 更新用户坐标位置
export const updateUserLocation = async (latitude: number, longitude: number) => {
try {
const response = await httpService.post('/user/update_location', {
latitude,
longitude,
});
return response;
} catch (error) {
console.error('更新用户坐标位置失败:', error);
throw error;
}
};
// 获取用户信息(从本地存储)
export const get_user_info = (): any | null => {
try {
let userinfo = Taro.getStorageSync('user_info')
if (userinfo) {
return JSON.parse(userinfo)
}
return null;
} catch (error) {
return null;
}
};

View File

@@ -16,7 +16,7 @@ interface GlobalState {
interface GlobalActions {
updateState: (payload: Record<string, any>) => void;
getNavbarHeightInfo: () => void;
getCurrentLocationInfo: () => void;
getCurrentLocationInfo: () => any;
}
// 完整的 Store 类型
type GlobalStore = GlobalState & GlobalActions;
@@ -50,14 +50,13 @@ export const useGlobalStore = create<GlobalStore>()((set, get) => ({
},
// 获取位置信息
getCurrentLocationInfo: () => {
return getCurrentLocation().then((res) => {
set({
getLocationLoading: false,
location: res || {},
});
return res;
getCurrentLocationInfo: async () => {
const res = await getCurrentLocation()
set({
getLocationLoading: false,
location: res || {},
});
return res;
},
// 更新store数据

View File

@@ -175,7 +175,7 @@ export const useListStore = create<TennisStore>()((set, get) => ({
// 第一次进入页面时传入 isRefresh 参数
if (isFirstLoad) {
reqParams.isRefresh = true;
reqParams.seachOption.isRefresh = true;
}
}

View File

@@ -1,13 +1,25 @@
import { create } from 'zustand'
import { fetchUserProfile, updateUserProfile, UserInfoType } from '@/services/loginService'
import { fetchUserProfile, updateUserProfile, UserInfoType } from '@/services/userService'
export interface UserState {
user: UserInfoType
loading: boolean
error: string | null
// 获取用户信息
fetchUserInfo: () => Promise<void>
updateUserInfo: (userInfo: Partial<UserInfoType>) => void
// 更新用户信息(先调用接口更新,再重新获取最新数据)
updateUserInfo: (userInfo: Partial<UserInfoType>) => Promise<void>
// 更新用户位置(特殊处理,需要重新获取详情数据)
updateUserLocation: (latitude: number, longitude: number) => Promise<void>
// 清除用户数据
clearUserData: () => void
}
export const useUser = create<UserState>()((set) => ({
export const useUser = create<UserState>()((set, get) => ({
user: {
id: 0,
"openid": "",
@@ -19,6 +31,7 @@ export const useUser = create<UserState>()((set) => ({
"country": "",
"province": "",
"city": "",
"district":"",
"language": "",
"phone": "13800138000",
"is_subscribed": "0",
@@ -27,20 +40,102 @@ export const useUser = create<UserState>()((set) => ({
"subscribe_time": "2024-06-15 14:00:00",
"last_login_time": "2024-06-15 14:00:00"
},
loading: false,
error: null,
// 获取用户信息
fetchUserInfo: async () => {
const res = await fetchUserProfile()
console.log(res)
set({ user: res.data })
try {
set({ loading: true, error: null })
const res = await fetchUserProfile()
if (res.code === 0) {
set({ user: res.data, loading: false })
} else {
set({ error: res.message || '获取用户信息失败', loading: false })
}
} catch (error) {
console.error('获取用户信息失败:', error)
set({ error: '获取用户信息失败', loading: false })
}
},
updateUserInfo: async(userInfo: Partial<UserInfoType>) => {
const res = await updateUserProfile(userInfo)
set({ user: res.data })
// 更新用户信息
updateUserInfo: async (userInfo: Partial<UserInfoType>) => {
try {
set({ loading: true, error: null })
// 先调用更新接口
const updateRes = await updateUserProfile(userInfo)
if (updateRes.code !== 0) {
throw new Error(updateRes.message || '更新用户信息失败')
}
// 更新成功后,重新获取最新的用户信息
await get().fetchUserInfo()
} catch (error) {
console.error('更新用户信息失败:', error)
set({ error: '更新用户信息失败', loading: false })
throw error
}
},
// 更新用户位置
updateUserLocation: async (latitude: number, longitude: number) => {
try {
set({ loading: true, error: null })
// 调用位置更新接口
const locationRes = await updateUserProfile({ latitude, longitude })
if (locationRes.code !== 0) {
throw new Error(locationRes.message || '更新位置失败')
}
// 位置更新成功后,重新获取最新的用户信息
await get().fetchUserInfo()
} catch (error) {
console.error('更新用户位置失败:', error)
set({ error: '更新用户位置失败', loading: false })
throw error
}
},
// 清除用户数据
clearUserData: () => {
set({
user: {
id: 0,
"openid": "",
"unionid": "",
"session_key": "",
"nickname": "",
"avatar_url": "",
"gender": "",
"country": "",
"province": "",
"city": "",
"language": "",
"phone": "",
"is_subscribed": "0",
"latitude": 0,
"longitude": 0,
"subscribe_time": "",
"last_login_time": ""
},
loading: false,
error: null
})
}
}))
export const useUserInfo = () => useUser((state) => state.user)
export const useUserLoading = () => useUser((state) => state.loading)
export const useUserError = () => useUser((state) => state.error)
export const useUserActions = () => useUser((state) => ({
fetchUserInfo: state.fetchUserInfo,
updateUserInfo: state.updateUserInfo
updateUserInfo: state.updateUserInfo,
updateUserLocation: state.updateUserLocation,
clearUserData: state.clearUserData
}))