index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { Image } from 'expo-image';
  2. import * as ImagePicker from 'expo-image-picker';
  3. import { useRouter } from 'expo-router';
  4. import React, { useEffect, useState } from 'react';
  5. import {
  6. Alert,
  7. ImageBackground,
  8. ScrollView,
  9. StatusBar,
  10. StyleSheet,
  11. Text,
  12. TextInput,
  13. TouchableOpacity,
  14. View,
  15. } from 'react-native';
  16. import { useSafeAreaInsets } from 'react-native-safe-area-context';
  17. import { Images } from '@/constants/images';
  18. import { useAuth } from '@/contexts/AuthContext';
  19. import { uploadFile } from '@/services/base';
  20. import { getUserInfo, updateAvatar, updateNickname, updateUserInfo } from '@/services/user';
  21. interface FormData {
  22. nickname: string;
  23. avatar: string;
  24. sex: number; // 1-男 2-女 3-保密
  25. }
  26. export default function ProfileScreen() {
  27. const router = useRouter();
  28. const insets = useSafeAreaInsets();
  29. const { refreshUser } = useAuth();
  30. const [formData, setFormData] = useState<FormData>({
  31. nickname: '',
  32. avatar: '',
  33. sex: 3,
  34. });
  35. const [loading, setLoading] = useState(false);
  36. useEffect(() => {
  37. loadUserInfo();
  38. }, []);
  39. const loadUserInfo = async () => {
  40. try {
  41. const res = await getUserInfo();
  42. if (res) {
  43. setFormData({
  44. nickname: res.nickname || '',
  45. avatar: res.avatar || '',
  46. sex: (res as any).sex || 3,
  47. });
  48. }
  49. } catch (error) {
  50. console.error('获取用户信息失败:', error);
  51. }
  52. };
  53. const handleBack = () => {
  54. router.back();
  55. };
  56. const handleChooseAvatar = async () => {
  57. try {
  58. const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  59. if (!permissionResult.granted) {
  60. Alert.alert('提示', '需要相册权限才能选择头像');
  61. return;
  62. }
  63. const result = await ImagePicker.launchImageLibraryAsync({
  64. mediaTypes: ['images'],
  65. allowsEditing: true,
  66. aspect: [1, 1],
  67. quality: 0.8,
  68. });
  69. if (!result.canceled && result.assets[0]) {
  70. const imageUri = result.assets[0].uri;
  71. setFormData(prev => ({ ...prev, avatar: imageUri }));
  72. }
  73. } catch (error) {
  74. console.error('选择头像失败:', error);
  75. Alert.alert('提示', '选择头像失败');
  76. }
  77. };
  78. const handleSexChange = (sex: number) => {
  79. setFormData(prev => ({ ...prev, sex }));
  80. };
  81. const handleSave = async () => {
  82. if (!formData.nickname?.trim()) {
  83. Alert.alert('提示', '请输入昵称');
  84. return;
  85. }
  86. try {
  87. setLoading(true);
  88. // 如果头像是本地文件(非http开头),需要先上传
  89. let avatarUrl = formData.avatar;
  90. console.log('[profile] 头像URI:', formData.avatar?.substring(0, 100));
  91. if (formData.avatar && !formData.avatar.startsWith('http')) {
  92. const uploadedUrl = await uploadFile(formData.avatar, 'avatar');
  93. if (uploadedUrl) {
  94. avatarUrl = uploadedUrl;
  95. // 更新头像
  96. await updateAvatar(avatarUrl);
  97. } else {
  98. Alert.alert('提示', '头像上传失败');
  99. setLoading(false);
  100. return;
  101. }
  102. }
  103. // 更新昵称
  104. const nicknameRes = await updateNickname(formData.nickname);
  105. // 更新其他信息(性别等)
  106. const infoRes = await updateUserInfo({ sex: formData.sex } as any);
  107. if (nicknameRes || infoRes) {
  108. Alert.alert('提示', '保存成功', [
  109. {
  110. text: '确定',
  111. onPress: () => {
  112. refreshUser?.();
  113. router.back();
  114. }
  115. }
  116. ]);
  117. } else {
  118. Alert.alert('提示', '保存失败');
  119. }
  120. } catch (error) {
  121. console.error('保存失败:', error);
  122. Alert.alert('提示', '保存失败');
  123. } finally {
  124. setLoading(false);
  125. }
  126. };
  127. return (
  128. <ImageBackground
  129. source={{ uri: Images.common.commonBg }}
  130. style={styles.container}
  131. resizeMode="cover"
  132. >
  133. <StatusBar barStyle="light-content" />
  134. {/* 顶部导航 */}
  135. <View style={[styles.header, { paddingTop: insets.top }]}>
  136. <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
  137. <Text style={styles.backIcon}>‹</Text>
  138. </TouchableOpacity>
  139. <Text style={styles.headerTitle}>个人资料</Text>
  140. <View style={styles.placeholder} />
  141. </View>
  142. <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
  143. {/* 头像 */}
  144. <TouchableOpacity style={styles.avatarSection} onPress={handleChooseAvatar}>
  145. <View style={styles.avatarWrapper}>
  146. <Image
  147. source={{ uri: formData.avatar || Images.common.defaultAvatar }}
  148. style={styles.avatar}
  149. contentFit="cover"
  150. />
  151. </View>
  152. <Text style={styles.avatarTip}>点击更换头像</Text>
  153. </TouchableOpacity>
  154. {/* 表单 */}
  155. <View style={styles.formSection}>
  156. {/* 昵称 */}
  157. <View style={styles.formItem}>
  158. <Text style={styles.formLabel}>昵称</Text>
  159. <TextInput
  160. style={styles.formInput}
  161. value={formData.nickname}
  162. onChangeText={(text) => setFormData(prev => ({ ...prev, nickname: text }))}
  163. placeholder="请输入昵称"
  164. placeholderTextColor="#999"
  165. maxLength={20}
  166. />
  167. </View>
  168. {/* 性别 */}
  169. <View style={styles.formItem}>
  170. <Text style={styles.formLabel}>性别</Text>
  171. <View style={styles.sexOptions}>
  172. <TouchableOpacity
  173. style={[styles.sexOption, formData.sex === 1 && styles.sexOptionActive]}
  174. onPress={() => handleSexChange(1)}
  175. >
  176. <View style={[styles.radioOuter, formData.sex === 1 && styles.radioOuterActive]}>
  177. {formData.sex === 1 && <View style={styles.radioInner} />}
  178. </View>
  179. <Text style={[styles.sexText, formData.sex === 1 && styles.sexTextActive]}>男</Text>
  180. </TouchableOpacity>
  181. <TouchableOpacity
  182. style={[styles.sexOption, formData.sex === 2 && styles.sexOptionActive]}
  183. onPress={() => handleSexChange(2)}
  184. >
  185. <View style={[styles.radioOuter, formData.sex === 2 && styles.radioOuterActive]}>
  186. {formData.sex === 2 && <View style={styles.radioInner} />}
  187. </View>
  188. <Text style={[styles.sexText, formData.sex === 2 && styles.sexTextActive]}>女</Text>
  189. </TouchableOpacity>
  190. <TouchableOpacity
  191. style={[styles.sexOption, formData.sex === 3 && styles.sexOptionActive]}
  192. onPress={() => handleSexChange(3)}
  193. >
  194. <View style={[styles.radioOuter, formData.sex === 3 && styles.radioOuterActive]}>
  195. {formData.sex === 3 && <View style={styles.radioInner} />}
  196. </View>
  197. <Text style={[styles.sexText, formData.sex === 3 && styles.sexTextActive]}>保密</Text>
  198. </TouchableOpacity>
  199. </View>
  200. </View>
  201. </View>
  202. {/* 保存按钮 */}
  203. <TouchableOpacity
  204. style={[styles.saveBtn, loading && styles.saveBtnDisabled]}
  205. onPress={handleSave}
  206. disabled={loading}
  207. >
  208. <ImageBackground
  209. source={{ uri: Images.common.loginBtn }}
  210. style={styles.saveBtnBg}
  211. resizeMode="contain"
  212. >
  213. <Text style={styles.saveBtnText}>{loading ? '保存中...' : '确定'}</Text>
  214. </ImageBackground>
  215. </TouchableOpacity>
  216. </ScrollView>
  217. </ImageBackground>
  218. );
  219. }
  220. const styles = StyleSheet.create({
  221. container: {
  222. flex: 1,
  223. },
  224. header: {
  225. flexDirection: 'row',
  226. alignItems: 'center',
  227. justifyContent: 'space-between',
  228. paddingHorizontal: 10,
  229. height: 80,
  230. },
  231. backBtn: {
  232. width: 40,
  233. height: 40,
  234. justifyContent: 'center',
  235. alignItems: 'center',
  236. },
  237. backIcon: {
  238. fontSize: 32,
  239. color: '#fff',
  240. fontWeight: 'bold',
  241. },
  242. headerTitle: {
  243. fontSize: 16,
  244. fontWeight: 'bold',
  245. color: '#fff',
  246. },
  247. placeholder: {
  248. width: 40,
  249. },
  250. scrollView: {
  251. flex: 1,
  252. paddingHorizontal: 20,
  253. },
  254. avatarSection: {
  255. alignItems: 'center',
  256. paddingVertical: 30,
  257. },
  258. avatarWrapper: {
  259. width: 80,
  260. height: 80,
  261. borderRadius: 40,
  262. borderWidth: 3,
  263. borderColor: '#FFE996',
  264. overflow: 'hidden',
  265. },
  266. avatar: {
  267. width: '100%',
  268. height: '100%',
  269. },
  270. avatarTip: {
  271. marginTop: 10,
  272. fontSize: 12,
  273. color: 'rgba(255,255,255,0.7)',
  274. },
  275. formSection: {
  276. backgroundColor: 'rgba(255,255,255,0.1)',
  277. borderRadius: 10,
  278. padding: 15,
  279. },
  280. formItem: {
  281. flexDirection: 'row',
  282. alignItems: 'center',
  283. paddingVertical: 15,
  284. borderBottomWidth: 1,
  285. borderBottomColor: 'rgba(255,255,255,0.2)',
  286. },
  287. formLabel: {
  288. width: 60,
  289. fontSize: 14,
  290. color: '#fff',
  291. },
  292. formInput: {
  293. flex: 1,
  294. fontSize: 14,
  295. color: '#fff',
  296. padding: 0,
  297. },
  298. sexOptions: {
  299. flex: 1,
  300. flexDirection: 'row',
  301. alignItems: 'center',
  302. },
  303. sexOption: {
  304. flexDirection: 'row',
  305. alignItems: 'center',
  306. marginRight: 20,
  307. },
  308. sexOptionActive: {},
  309. radioOuter: {
  310. width: 18,
  311. height: 18,
  312. borderRadius: 9,
  313. borderWidth: 2,
  314. borderColor: 'rgba(255,255,255,0.5)',
  315. justifyContent: 'center',
  316. alignItems: 'center',
  317. marginRight: 6,
  318. },
  319. radioOuterActive: {
  320. borderColor: '#FC7D2E',
  321. },
  322. radioInner: {
  323. width: 10,
  324. height: 10,
  325. borderRadius: 5,
  326. backgroundColor: '#FC7D2E',
  327. },
  328. sexText: {
  329. fontSize: 14,
  330. color: 'rgba(255,255,255,0.7)',
  331. },
  332. sexTextActive: {
  333. color: '#fff',
  334. },
  335. saveBtn: {
  336. marginTop: 50,
  337. alignItems: 'center',
  338. },
  339. saveBtnDisabled: {
  340. opacity: 0.6,
  341. },
  342. saveBtnBg: {
  343. width: 280,
  344. height: 60,
  345. justifyContent: 'center',
  346. alignItems: 'center',
  347. },
  348. saveBtnText: {
  349. fontSize: 16,
  350. fontWeight: 'bold',
  351. color: '#fff',
  352. textShadowColor: '#000',
  353. textShadowOffset: { width: 1, height: 1 },
  354. textShadowRadius: 2,
  355. },
  356. });