| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- import { Image } from 'expo-image';
- import * as ImagePicker from 'expo-image-picker';
- import { useRouter } from 'expo-router';
- import React, { useEffect, useState } from 'react';
- import {
- Alert,
- ImageBackground,
- ScrollView,
- StatusBar,
- StyleSheet,
- Text,
- TextInput,
- TouchableOpacity,
- View,
- } from 'react-native';
- import { useSafeAreaInsets } from 'react-native-safe-area-context';
- import { Images } from '@/constants/images';
- import { useAuth } from '@/contexts/AuthContext';
- import { uploadFile } from '@/services/base';
- import { getUserInfo, updateAvatar, updateNickname, updateUserInfo } from '@/services/user';
- interface FormData {
- nickname: string;
- avatar: string;
- sex: number; // 1-男 2-女 3-保密
- }
- export default function ProfileScreen() {
- const router = useRouter();
- const insets = useSafeAreaInsets();
- const { refreshUser } = useAuth();
-
- const [formData, setFormData] = useState<FormData>({
- nickname: '',
- avatar: '',
- sex: 3,
- });
- const [loading, setLoading] = useState(false);
- useEffect(() => {
- loadUserInfo();
- }, []);
- const loadUserInfo = async () => {
- try {
- const res = await getUserInfo();
- if (res) {
- setFormData({
- nickname: res.nickname || '',
- avatar: res.avatar || '',
- sex: (res as any).sex || 3,
- });
- }
- } catch (error) {
- console.error('获取用户信息失败:', error);
- }
- };
- const handleBack = () => {
- router.back();
- };
- const handleChooseAvatar = async () => {
- try {
- const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
- if (!permissionResult.granted) {
- Alert.alert('提示', '需要相册权限才能选择头像');
- return;
- }
- const result = await ImagePicker.launchImageLibraryAsync({
- mediaTypes: ['images'],
- allowsEditing: true,
- aspect: [1, 1],
- quality: 0.8,
- });
- if (!result.canceled && result.assets[0]) {
- const imageUri = result.assets[0].uri;
- setFormData(prev => ({ ...prev, avatar: imageUri }));
- }
- } catch (error) {
- console.error('选择头像失败:', error);
- Alert.alert('提示', '选择头像失败');
- }
- };
- const handleSexChange = (sex: number) => {
- setFormData(prev => ({ ...prev, sex }));
- };
- const handleSave = async () => {
- if (!formData.nickname?.trim()) {
- Alert.alert('提示', '请输入昵称');
- return;
- }
- try {
- setLoading(true);
-
- // 如果头像是本地文件(file://开头),需要先上传
- let avatarUrl = formData.avatar;
- if (formData.avatar && formData.avatar.startsWith('file://')) {
- const uploadedUrl = await uploadFile(formData.avatar, 'avatar');
- if (uploadedUrl) {
- avatarUrl = uploadedUrl;
- // 更新头像
- await updateAvatar(avatarUrl);
- } else {
- Alert.alert('提示', '头像上传失败');
- setLoading(false);
- return;
- }
- }
-
- // 更新昵称
- const nicknameRes = await updateNickname(formData.nickname);
-
- // 更新其他信息(性别等)
- const infoRes = await updateUserInfo({ sex: formData.sex } as any);
-
- if (nicknameRes || infoRes) {
- Alert.alert('提示', '保存成功', [
- {
- text: '确定',
- onPress: () => {
- refreshUser?.();
- router.back();
- }
- }
- ]);
- } else {
- Alert.alert('提示', '保存失败');
- }
- } catch (error) {
- console.error('保存失败:', error);
- Alert.alert('提示', '保存失败');
- } finally {
- setLoading(false);
- }
- };
- return (
- <ImageBackground
- source={{ uri: Images.common.commonBg }}
- style={styles.container}
- resizeMode="cover"
- >
- <StatusBar barStyle="light-content" />
-
- {/* 顶部导航 */}
- <View style={[styles.header, { paddingTop: insets.top }]}>
- <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
- <Text style={styles.backIcon}>‹</Text>
- </TouchableOpacity>
- <Text style={styles.headerTitle}>个人资料</Text>
- <View style={styles.placeholder} />
- </View>
- <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
- {/* 头像 */}
- <TouchableOpacity style={styles.avatarSection} onPress={handleChooseAvatar}>
- <View style={styles.avatarWrapper}>
- <Image
- source={{ uri: formData.avatar || Images.common.defaultAvatar }}
- style={styles.avatar}
- contentFit="cover"
- />
- </View>
- <Text style={styles.avatarTip}>点击更换头像</Text>
- </TouchableOpacity>
- {/* 表单 */}
- <View style={styles.formSection}>
- {/* 昵称 */}
- <View style={styles.formItem}>
- <Text style={styles.formLabel}>昵称</Text>
- <TextInput
- style={styles.formInput}
- value={formData.nickname}
- onChangeText={(text) => setFormData(prev => ({ ...prev, nickname: text }))}
- placeholder="请输入昵称"
- placeholderTextColor="#999"
- maxLength={20}
- />
- </View>
- {/* 性别 */}
- <View style={styles.formItem}>
- <Text style={styles.formLabel}>性别</Text>
- <View style={styles.sexOptions}>
- <TouchableOpacity
- style={[styles.sexOption, formData.sex === 1 && styles.sexOptionActive]}
- onPress={() => handleSexChange(1)}
- >
- <View style={[styles.radioOuter, formData.sex === 1 && styles.radioOuterActive]}>
- {formData.sex === 1 && <View style={styles.radioInner} />}
- </View>
- <Text style={[styles.sexText, formData.sex === 1 && styles.sexTextActive]}>男</Text>
- </TouchableOpacity>
- <TouchableOpacity
- style={[styles.sexOption, formData.sex === 2 && styles.sexOptionActive]}
- onPress={() => handleSexChange(2)}
- >
- <View style={[styles.radioOuter, formData.sex === 2 && styles.radioOuterActive]}>
- {formData.sex === 2 && <View style={styles.radioInner} />}
- </View>
- <Text style={[styles.sexText, formData.sex === 2 && styles.sexTextActive]}>女</Text>
- </TouchableOpacity>
- <TouchableOpacity
- style={[styles.sexOption, formData.sex === 3 && styles.sexOptionActive]}
- onPress={() => handleSexChange(3)}
- >
- <View style={[styles.radioOuter, formData.sex === 3 && styles.radioOuterActive]}>
- {formData.sex === 3 && <View style={styles.radioInner} />}
- </View>
- <Text style={[styles.sexText, formData.sex === 3 && styles.sexTextActive]}>保密</Text>
- </TouchableOpacity>
- </View>
- </View>
- </View>
- {/* 保存按钮 */}
- <TouchableOpacity
- style={[styles.saveBtn, loading && styles.saveBtnDisabled]}
- onPress={handleSave}
- disabled={loading}
- >
- <ImageBackground
- source={{ uri: Images.common.loginBtn }}
- style={styles.saveBtnBg}
- resizeMode="contain"
- >
- <Text style={styles.saveBtnText}>{loading ? '保存中...' : '确定'}</Text>
- </ImageBackground>
- </TouchableOpacity>
- </ScrollView>
- </ImageBackground>
- );
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,
- },
- header: {
- flexDirection: 'row',
- alignItems: 'center',
- justifyContent: 'space-between',
- paddingHorizontal: 10,
- height: 80,
- },
- backBtn: {
- width: 40,
- height: 40,
- justifyContent: 'center',
- alignItems: 'center',
- },
- backIcon: {
- fontSize: 32,
- color: '#fff',
- fontWeight: 'bold',
- },
- headerTitle: {
- fontSize: 16,
- fontWeight: 'bold',
- color: '#fff',
- },
- placeholder: {
- width: 40,
- },
- scrollView: {
- flex: 1,
- paddingHorizontal: 20,
- },
- avatarSection: {
- alignItems: 'center',
- paddingVertical: 30,
- },
- avatarWrapper: {
- width: 80,
- height: 80,
- borderRadius: 40,
- borderWidth: 3,
- borderColor: '#FFE996',
- overflow: 'hidden',
- },
- avatar: {
- width: '100%',
- height: '100%',
- },
- avatarTip: {
- marginTop: 10,
- fontSize: 12,
- color: 'rgba(255,255,255,0.7)',
- },
- formSection: {
- backgroundColor: 'rgba(255,255,255,0.1)',
- borderRadius: 10,
- padding: 15,
- },
- formItem: {
- flexDirection: 'row',
- alignItems: 'center',
- paddingVertical: 15,
- borderBottomWidth: 1,
- borderBottomColor: 'rgba(255,255,255,0.2)',
- },
- formLabel: {
- width: 60,
- fontSize: 14,
- color: '#fff',
- },
- formInput: {
- flex: 1,
- fontSize: 14,
- color: '#fff',
- padding: 0,
- },
- sexOptions: {
- flex: 1,
- flexDirection: 'row',
- alignItems: 'center',
- },
- sexOption: {
- flexDirection: 'row',
- alignItems: 'center',
- marginRight: 20,
- },
- sexOptionActive: {},
- radioOuter: {
- width: 18,
- height: 18,
- borderRadius: 9,
- borderWidth: 2,
- borderColor: 'rgba(255,255,255,0.5)',
- justifyContent: 'center',
- alignItems: 'center',
- marginRight: 6,
- },
- radioOuterActive: {
- borderColor: '#FC7D2E',
- },
- radioInner: {
- width: 10,
- height: 10,
- borderRadius: 5,
- backgroundColor: '#FC7D2E',
- },
- sexText: {
- fontSize: 14,
- color: 'rgba(255,255,255,0.7)',
- },
- sexTextActive: {
- color: '#fff',
- },
- saveBtn: {
- marginTop: 50,
- alignItems: 'center',
- },
- saveBtnDisabled: {
- opacity: 0.6,
- },
- saveBtnBg: {
- width: 280,
- height: 60,
- justifyContent: 'center',
- alignItems: 'center',
- },
- saveBtnText: {
- fontSize: 16,
- fontWeight: 'bold',
- color: '#fff',
- textShadowColor: '#000',
- textShadowOffset: { width: 1, height: 1 },
- textShadowRadius: 2,
- },
- });
|