index.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. // 如果头像是本地文件(file://开头),需要先上传
  89. let avatarUrl = formData.avatar;
  90. if (formData.avatar && formData.avatar.startsWith('file://')) {
  91. const uploadedUrl = await uploadFile(formData.avatar, 'avatar');
  92. if (uploadedUrl) {
  93. avatarUrl = uploadedUrl;
  94. // 更新头像
  95. await updateAvatar(avatarUrl);
  96. } else {
  97. Alert.alert('提示', '头像上传失败');
  98. setLoading(false);
  99. return;
  100. }
  101. }
  102. // 更新昵称
  103. const nicknameRes = await updateNickname(formData.nickname);
  104. // 更新其他信息(性别等)
  105. const infoRes = await updateUserInfo({ sex: formData.sex } as any);
  106. if (nicknameRes || infoRes) {
  107. Alert.alert('提示', '保存成功', [
  108. {
  109. text: '确定',
  110. onPress: () => {
  111. refreshUser?.();
  112. router.back();
  113. }
  114. }
  115. ]);
  116. } else {
  117. Alert.alert('提示', '保存失败');
  118. }
  119. } catch (error) {
  120. console.error('保存失败:', error);
  121. Alert.alert('提示', '保存失败');
  122. } finally {
  123. setLoading(false);
  124. }
  125. };
  126. return (
  127. <ImageBackground
  128. source={{ uri: Images.common.commonBg }}
  129. style={styles.container}
  130. resizeMode="cover"
  131. >
  132. <StatusBar barStyle="light-content" />
  133. {/* 顶部导航 */}
  134. <View style={[styles.header, { paddingTop: insets.top }]}>
  135. <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
  136. <Text style={styles.backIcon}>‹</Text>
  137. </TouchableOpacity>
  138. <Text style={styles.headerTitle}>个人资料</Text>
  139. <View style={styles.placeholder} />
  140. </View>
  141. <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
  142. {/* 头像 */}
  143. <TouchableOpacity style={styles.avatarSection} onPress={handleChooseAvatar}>
  144. <View style={styles.avatarWrapper}>
  145. <Image
  146. source={{ uri: formData.avatar || Images.common.defaultAvatar }}
  147. style={styles.avatar}
  148. contentFit="cover"
  149. />
  150. </View>
  151. <Text style={styles.avatarTip}>点击更换头像</Text>
  152. </TouchableOpacity>
  153. {/* 表单 */}
  154. <View style={styles.formSection}>
  155. {/* 昵称 */}
  156. <View style={styles.formItem}>
  157. <Text style={styles.formLabel}>昵称</Text>
  158. <TextInput
  159. style={styles.formInput}
  160. value={formData.nickname}
  161. onChangeText={(text) => setFormData(prev => ({ ...prev, nickname: text }))}
  162. placeholder="请输入昵称"
  163. placeholderTextColor="#999"
  164. maxLength={20}
  165. />
  166. </View>
  167. {/* 性别 */}
  168. <View style={styles.formItem}>
  169. <Text style={styles.formLabel}>性别</Text>
  170. <View style={styles.sexOptions}>
  171. <TouchableOpacity
  172. style={[styles.sexOption, formData.sex === 1 && styles.sexOptionActive]}
  173. onPress={() => handleSexChange(1)}
  174. >
  175. <View style={[styles.radioOuter, formData.sex === 1 && styles.radioOuterActive]}>
  176. {formData.sex === 1 && <View style={styles.radioInner} />}
  177. </View>
  178. <Text style={[styles.sexText, formData.sex === 1 && styles.sexTextActive]}>男</Text>
  179. </TouchableOpacity>
  180. <TouchableOpacity
  181. style={[styles.sexOption, formData.sex === 2 && styles.sexOptionActive]}
  182. onPress={() => handleSexChange(2)}
  183. >
  184. <View style={[styles.radioOuter, formData.sex === 2 && styles.radioOuterActive]}>
  185. {formData.sex === 2 && <View style={styles.radioInner} />}
  186. </View>
  187. <Text style={[styles.sexText, formData.sex === 2 && styles.sexTextActive]}>女</Text>
  188. </TouchableOpacity>
  189. <TouchableOpacity
  190. style={[styles.sexOption, formData.sex === 3 && styles.sexOptionActive]}
  191. onPress={() => handleSexChange(3)}
  192. >
  193. <View style={[styles.radioOuter, formData.sex === 3 && styles.radioOuterActive]}>
  194. {formData.sex === 3 && <View style={styles.radioInner} />}
  195. </View>
  196. <Text style={[styles.sexText, formData.sex === 3 && styles.sexTextActive]}>保密</Text>
  197. </TouchableOpacity>
  198. </View>
  199. </View>
  200. </View>
  201. {/* 保存按钮 */}
  202. <TouchableOpacity
  203. style={[styles.saveBtn, loading && styles.saveBtnDisabled]}
  204. onPress={handleSave}
  205. disabled={loading}
  206. >
  207. <ImageBackground
  208. source={{ uri: Images.common.loginBtn }}
  209. style={styles.saveBtnBg}
  210. resizeMode="contain"
  211. >
  212. <Text style={styles.saveBtnText}>{loading ? '保存中...' : '确定'}</Text>
  213. </ImageBackground>
  214. </TouchableOpacity>
  215. </ScrollView>
  216. </ImageBackground>
  217. );
  218. }
  219. const styles = StyleSheet.create({
  220. container: {
  221. flex: 1,
  222. },
  223. header: {
  224. flexDirection: 'row',
  225. alignItems: 'center',
  226. justifyContent: 'space-between',
  227. paddingHorizontal: 10,
  228. height: 80,
  229. },
  230. backBtn: {
  231. width: 40,
  232. height: 40,
  233. justifyContent: 'center',
  234. alignItems: 'center',
  235. },
  236. backIcon: {
  237. fontSize: 32,
  238. color: '#fff',
  239. fontWeight: 'bold',
  240. },
  241. headerTitle: {
  242. fontSize: 16,
  243. fontWeight: 'bold',
  244. color: '#fff',
  245. },
  246. placeholder: {
  247. width: 40,
  248. },
  249. scrollView: {
  250. flex: 1,
  251. paddingHorizontal: 20,
  252. },
  253. avatarSection: {
  254. alignItems: 'center',
  255. paddingVertical: 30,
  256. },
  257. avatarWrapper: {
  258. width: 80,
  259. height: 80,
  260. borderRadius: 40,
  261. borderWidth: 3,
  262. borderColor: '#FFE996',
  263. overflow: 'hidden',
  264. },
  265. avatar: {
  266. width: '100%',
  267. height: '100%',
  268. },
  269. avatarTip: {
  270. marginTop: 10,
  271. fontSize: 12,
  272. color: 'rgba(255,255,255,0.7)',
  273. },
  274. formSection: {
  275. backgroundColor: 'rgba(255,255,255,0.1)',
  276. borderRadius: 10,
  277. padding: 15,
  278. },
  279. formItem: {
  280. flexDirection: 'row',
  281. alignItems: 'center',
  282. paddingVertical: 15,
  283. borderBottomWidth: 1,
  284. borderBottomColor: 'rgba(255,255,255,0.2)',
  285. },
  286. formLabel: {
  287. width: 60,
  288. fontSize: 14,
  289. color: '#fff',
  290. },
  291. formInput: {
  292. flex: 1,
  293. fontSize: 14,
  294. color: '#fff',
  295. padding: 0,
  296. },
  297. sexOptions: {
  298. flex: 1,
  299. flexDirection: 'row',
  300. alignItems: 'center',
  301. },
  302. sexOption: {
  303. flexDirection: 'row',
  304. alignItems: 'center',
  305. marginRight: 20,
  306. },
  307. sexOptionActive: {},
  308. radioOuter: {
  309. width: 18,
  310. height: 18,
  311. borderRadius: 9,
  312. borderWidth: 2,
  313. borderColor: 'rgba(255,255,255,0.5)',
  314. justifyContent: 'center',
  315. alignItems: 'center',
  316. marginRight: 6,
  317. },
  318. radioOuterActive: {
  319. borderColor: '#FC7D2E',
  320. },
  321. radioInner: {
  322. width: 10,
  323. height: 10,
  324. borderRadius: 5,
  325. backgroundColor: '#FC7D2E',
  326. },
  327. sexText: {
  328. fontSize: 14,
  329. color: 'rgba(255,255,255,0.7)',
  330. },
  331. sexTextActive: {
  332. color: '#fff',
  333. },
  334. saveBtn: {
  335. marginTop: 50,
  336. alignItems: 'center',
  337. },
  338. saveBtnDisabled: {
  339. opacity: 0.6,
  340. },
  341. saveBtnBg: {
  342. width: 280,
  343. height: 60,
  344. justifyContent: 'center',
  345. alignItems: 'center',
  346. },
  347. saveBtnText: {
  348. fontSize: 16,
  349. fontWeight: 'bold',
  350. color: '#fff',
  351. textShadowColor: '#000',
  352. textShadowOffset: { width: 1, height: 1 },
  353. textShadowRadius: 2,
  354. },
  355. });