import 'dart:io'; import 'package:dating_touchme_app/controller/global.dart'; import 'package:dating_touchme_app/generated/assets.dart'; import 'package:dating_touchme_app/model/home/marriage_data.dart'; import 'package:dating_touchme_app/model/mine/address_data.dart'; import 'package:dating_touchme_app/model/mine/education_data.dart'; import 'package:dating_touchme_app/model/mine/occupation_data.dart'; import 'package:dating_touchme_app/model/mine/user_data.dart'; import 'package:dating_touchme_app/network/user_api.dart'; import 'package:dating_touchme_app/oss/oss_manager.dart'; import 'package:dating_touchme_app/pages/home/user_information_page.dart'; import 'package:dating_touchme_app/pages/mine/auth_center_page.dart'; import 'package:dating_touchme_app/pages/mine/my_wallet_page.dart'; import 'package:dating_touchme_app/pages/mine/rose_page.dart'; import 'package:flustars/flustars.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:get_storage/get_storage.dart'; import 'package:image_picker/image_picker.dart'; import 'package:image_picker_android/image_picker_android.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import '../../model/home/user_info_data.dart'; class EditInfoController extends GetxController { late UserApi _userApi; final menuActive = 1.obs; final nowSelect = 0.obs; List tagList = [ "北京", "160cm", "想要甜甜的恋爱", "本科", "朋友圈摄影师", "英雄联盟", "流放之路", "CF", "DNA", "堡垒之夜", "SCP" ]; final userData = GlobalData().userData.obs; final height = ''.obs; final heightController = TextEditingController().obs; final heightList = [for (var i = 140; i <= 210; i++) "$i"].obs; final heightSelect = (-1).obs; final educationList = [].obs; final incomeList = [].obs; final maritalList = [].obs; final propertyList = [].obs; final occupationList = [].obs; final occupationShowData = {}.obs; final areaShowData = {}.obs; final avatarUrl = ''.obs; // 本地选择的头像文件路径(提交时先上传) final avatarLocalPath = ''.obs; final imgList = [].obs; final location = "".obs; final locationValue = [].obs; final homeLocation = "".obs; final homeLocationValue = [].obs; final educationSelect = (-1).obs; final occupation = "".obs; final occupationValue = [].obs; final incomeSelect = (-1).obs; final maritalSelect = (-1).obs; final propertySelect = (-1).obs; final storage = GetStorage(); @override void onInit() { super.onInit(); userData.value = GlobalData().userData; final ImagePickerPlatform imagePickerImplementation = ImagePickerPlatform.instance; if (imagePickerImplementation is ImagePickerAndroid) { imagePickerImplementation.useAndroidPhotoPicker = true; } _userApi = Get.find(); getEducationList(); getIncomeList(); getMaritalList(); getPropertyList(); getOccupationList(); getAreaShow(); setData(); } getEducationList() async { try { final response = await _userApi.getEducationList({}); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; educationList.clear(); educationList.addAll(data?.toList() ?? []); educationSelect.value = educationList.indexWhere((e){ return e.value == userData.value?.educationCode; }); } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('学历列表获取失败: $e'); SmartDialog.showToast('学历列表获取失败'); rethrow; } } getIncomeList() async { try { final response = await _userApi.getIncomeList({}); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; incomeList.clear(); incomeList.addAll(data?.toList() ?? []); incomeSelect.value = incomeList.indexWhere((e){ return e.value == userData.value?.incomeCode; }); } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('收入列表获取失败: $e'); SmartDialog.showToast('收入列表获取失败'); rethrow; } } getMaritalList() async { try { final response = await _userApi.getMaritalStatusList({}); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; maritalList.clear(); maritalList.addAll(data?.toList() ?? []); maritalSelect.value = maritalList.indexWhere((e){ return e.value == userData.value?.maritalStatusCode; }); } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('收入列表获取失败: $e'); SmartDialog.showToast('收入列表获取失败'); rethrow; } } getPropertyList() async { try { final response = await _userApi.getPropertyList({}); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; propertyList.clear(); propertyList.addAll(data?.toList() ?? []); propertySelect.value = propertyList.indexWhere((e){ return e.value == userData.value?.propertyPermitsCode; }); } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('收入列表获取失败: $e'); SmartDialog.showToast('收入列表获取失败'); rethrow; } } getOccupationList() async { try { final response = await _userApi.getOccupationList({}); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; occupationList.clear(); occupationList.addAll(data?.toList() ?? []); for(int i = 0; i < occupationList.length; i++){ occupationShowData[occupationList[i].industry] = occupationList[i].occupationList?.map((e){ return e.occupation; }).toList(); } final outerIndex = occupationList.indexWhere((outer) => outer.occupationList!.any((child) => child.occupationCode == userData.value?.occupationCode)); if (outerIndex != -1) { final innerIndex = occupationList[outerIndex].occupationList !.indexWhere((child) => child.occupationCode == userData.value?.occupationCode); print("outerIndex = $outerIndex, innerIndex = $innerIndex"); occupation.value = "${occupationList[outerIndex].industry}-${occupationList[outerIndex].occupationList![innerIndex].occupation}"; occupationValue.value = [occupationList[outerIndex].industryCode, occupationList[outerIndex].occupationList![innerIndex].occupationCode]; print(occupation.value); print(occupationValue.value); } } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('收入列表获取失败: $e'); SmartDialog.showToast('收入列表获取失败'); rethrow; } } getAreaShow() async { for(int i = 0; i < address.length; i++){ areaShowData[address[i]["label"]] = {}; for(int j = 0; j < address[i]["children"].length; j++){ areaShowData[address[i]["label"]][address[i]["children"][j]["label"]] = address[i]["children"][j]["children"].map((e){ return e["label"]; }).toList(); } } print(areaShowData); } setData(){ imgList.value = userData.value?.photoList?.map((e){ return e.photoUrl; }).toList() ?? []; heightSelect.value = heightList.indexWhere((e) => e == "${userData.value?.height}"); // height.value = userData.value?.height.toString() ?? ""; // heightController.value.value = TextEditingValue( // text: height.value, // selection: TextSelection.fromPosition(TextPosition(offset: height.value.length)), // ); if(userData.value?.provinceName != "" && userData.value?.cityName != "" && userData.value?.districtName != "" && userData.value?.provinceName != null && userData.value?.cityName != null && userData.value?.districtName != null){ location.value = "${userData.value?.provinceName}-${userData.value?.cityName}-${userData.value?.districtName}"; locationValue.value = [userData.value?.provinceCode, userData.value?.cityCode, userData.value?.districtCode]; } if(userData.value?.hometownProvinceName != "" && userData.value?.hometownCityName != "" && userData.value?.hometownProvinceName != null && userData.value?.hometownCityName != null){ homeLocation.value = "${userData.value?.hometownProvinceName}-${userData.value?.hometownCityName}"; homeLocationValue.value = [userData.value?.hometownProvinceCode, userData.value?.hometownCityCode]; } } goPreview() async { try { final response = await _userApi.getMarriageInformationDetailsById(miId: userData.value?.id ?? ""); if (response.data.isSuccess && response.data.data != null) { final data = response.data.data; Get.to(() => UserInformationPage(userData: MarriageData( miId: data?.miId ?? "", userId: data?.userId ?? "", profilePhoto: data?.profilePhoto ?? "", nickName: data?.nickName ?? "", isRealNameCertified: data?.identityCard == null, birthYear: data?.birthYear ?? "", birthDate: data?.birthDate ?? "", age: int.parse(data?.age.toString() ?? "0"), provinceCode: int.parse(data?.provinceCode.toString() ?? "0"), provinceName: data?.provinceName ?? "", cityCode: int.parse(data?.cityCode.toString() ?? "0"), cityName: data?.cityName ?? "", districtCode: int.parse(data?.districtCode.toString() ?? "0"), districtName: data?.districtName ?? "", describeInfo: data?.describeInfo ?? "", createTime: data?.createTime ?? "", photoList: data!.photoList!.map((e){ return PhotoItem.fromJson(e.toJson()); }).toList(), ))); } else { // 响应失败,抛出异常 throw Exception(response.data.message ?? '获取数据失败'); } } catch(e){ print('收入列表获取失败: $e'); SmartDialog.showToast('收入列表获取失败'); rethrow; } } int calculateAge(String birthdayStr) { final birthday = DateTime.parse(birthdayStr); // 自动识别 1996-1-20 final today = DateTime.now(); int age = today.year - birthday.year; // 如果今年生日还没过,年龄要减 1 if (today.month < birthday.month || (today.month == birthday.month && today.day < birthday.day)) { age--; } return age; } // 选择头像 - 业务逻辑处理 Future handleCameraCapture(int type) async { try { // 请求相机权限 final ok = await _ensurePermission( Permission.camera, denyToast: '相机权限被拒绝,请在设置中允许访问相机', ); if (!ok) return; // 请求麦克风权限(部分设备拍照/录像会一并请求建议预授权) await _ensurePermission(Permission.microphone, denyToast: '麦克风权限被拒绝'); // 权限通过后拍照 final ImagePicker picker = ImagePicker(); final XFile? photo = await picker.pickImage(source: ImageSource.camera); if (photo != null) { if(type == 1){ avatarLocalPath.value = photo.path; } await processSelectedImage(File(photo.path), type); } } catch (e) { print('拍照失败: $e'); // 更友好的错误提示 if (e.toString().contains('permission') || e.toString().contains('权限')) { SmartDialog.showToast('相机权限被拒绝,请在设置中允许访问相机'); } else if (e.toString().contains('camera') || e.toString().contains('相机')) { SmartDialog.showToast('设备没有可用的相机'); } else { SmartDialog.showToast('拍照失败,请重试'); } } } Future handleGallerySelection(int type) async { try { // 请求相册/照片权限 // final ok = await _ensurePermission( // Permission.photos, // // Android 上 photos 等价于 storage/mediaLibrary,permission_handler 会映射 // denyToast: '相册权限被拒绝,请在设置中允许访问相册', // ); // if (!ok) return; // 从相册选择图片 final ImagePicker picker = ImagePicker(); final XFile? image = await picker.pickImage(source: ImageSource.gallery); if (image != null) { if(type == 1){ avatarLocalPath.value = image.path; } await processSelectedImage(File(image.path), type); } } catch (e) { print('选择图片失败: $e'); // 更友好的错误提示 if (e.toString().contains('permission') || e.toString().contains('权限')) { SmartDialog.showToast('相册权限被拒绝,请在设置中允许访问相册'); } else { SmartDialog.showToast('选择图片失败,请重试'); } } } Future handleMultiGallerySelection(int type) async { try { // 请求相册/照片权限 // final ok = await _ensurePermission( // Permission.photos, // // Android 上 photos 等价于 storage/mediaLibrary,permission_handler 会映射 // denyToast: '相册权限被拒绝,请在设置中允许访问相册', // ); // if (!ok) return; // 从相册选择图片 final ImagePicker picker = ImagePicker(); final List? image = await picker.pickMultiImage(limit: 9 - imgList.length); if (image != null) { for(int i = 0; i _ensurePermission(Permission permission, {String? denyToast}) async { var status = await permission.status; if (status.isGranted) return true; if (status.isDenied || status.isRestricted || status.isLimited) { status = await permission.request(); if (status.isGranted) return true; if (denyToast != null) SmartDialog.showToast(denyToast); return false; } if (status.isPermanentlyDenied) { if (denyToast != null) SmartDialog.showToast('$denyToast,前往系统设置开启'); // 延迟弹设置,避免与弹窗冲突 Future.delayed(const Duration(milliseconds: 300), openAppSettings); return false; } return false; } // 处理选中的图片 Future processSelectedImage(File imageFile, int type) async { if(type == 1){ try { // 显示加载提示 SmartDialog.showLoading(msg: '上传头像中...'); String objectName = '${DateUtil.getNowDateMs()}.${imageFile.path.split('.').last}'; String imageUrl = await OSSManager.instance.uploadFile(imageFile.readAsBytesSync(), objectName); print('上传成功,图片URL: $imageUrl'); avatarUrl.value = imageUrl; SmartDialog.dismiss(); SmartDialog.showToast('头像上传成功'); saveAvatar(); } catch (e) { SmartDialog.dismiss(); print('处理图片失败: $e'); SmartDialog.showToast('上传头像失败,请重试'); } } else { try { // 显示加载提示 SmartDialog.showLoading(msg: '上传相册中...'); String objectName = '${DateUtil.getNowDateMs()}.${imageFile.path.split('.').last}'; String imageUrl = await OSSManager.instance.uploadFile(imageFile.readAsBytesSync(), objectName); print('上传成功,图片URL: $imageUrl'); imgList.add(imageUrl); SmartDialog.dismiss(); SmartDialog.showToast('相册上传成功'); savaImgList(); } catch (e) { SmartDialog.dismiss(); print('处理图片失败: $e'); SmartDialog.showToast('上传相册失败,请重试'); } } } // 处理选中的图片 Future processSelectedMoreImage(File imageFile, int type) async { if(type == 1){ try { // 显示加载提示 SmartDialog.showLoading(msg: '上传头像中...'); String objectName = '${DateUtil.getNowDateMs()}.${imageFile.path.split('.').last}'; String imageUrl = await OSSManager.instance.uploadFile(imageFile.readAsBytesSync(), objectName); print('上传成功,图片URL: $imageUrl'); avatarUrl.value = imageUrl; SmartDialog.dismiss(); SmartDialog.showToast('头像上传成功'); saveAvatar(); } catch (e) { SmartDialog.dismiss(); print('处理图片失败: $e'); SmartDialog.showToast('上传头像失败,请重试'); } } else { try { // 显示加载提示 SmartDialog.showLoading(msg: '上传相册中...'); String objectName = '${DateUtil.getNowDateMs()}.${imageFile.path.split('.').last}'; String imageUrl = await OSSManager.instance.uploadFile(imageFile.readAsBytesSync(), objectName); print('上传成功,图片URL: $imageUrl'); imgList.add(imageUrl); } catch (e) { SmartDialog.dismiss(); print('处理图片失败: $e'); SmartDialog.showToast('上传相册失败,请重试'); } } } saveAvatar() async { try { final avatarPayload = { 'miId': userData.value?.id ?? 0, 'authenticationCode': '8', 'value': '0', 'imgUrl': avatarUrl.value.isNotEmpty ? [avatarUrl.value] : ['0'], }; final avatarAuditResp = await _userApi.saveCertificationAudit(avatarPayload); if (avatarAuditResp.data.isSuccess) { } else{ SmartDialog.showToast(avatarAuditResp.data.message); return; } } catch(e){ print('头像提交审核失败: $e'); SmartDialog.showToast('头像提交审核失败,请重试'); return; } } savaImgList() async { try{ final imgPayload = { 'miId': userData.value?.id ?? 0, 'authenticationCode': '6', 'value': '0', 'imgUrl': imgList.isNotEmpty ? imgList : ['0'], }; final imgAuditResp = await _userApi.saveCertificationAudit(imgPayload); if (imgAuditResp.data.isSuccess) { } else{ SmartDialog.showToast(imgAuditResp.data.message); return; } } catch(e){ print('相册提交审核失败: $e'); SmartDialog.showToast('相册提交审核失败,请重试'); return; } } saveData() async { try { final payload = { 'birthDate': userData.value?.birthDate ?? "", 'birthYear': userData.value?.birthYear ?? "", 'provinceCode': locationValue.length >= 3 ? locationValue[0] : "", 'provinceName': location.value != "" ? location.value.split("-")[0] : "", 'cityCode': locationValue.length >= 3 ? locationValue[1] : "", 'cityName': location.value != "" ? location.value.split("-")[1] : "", 'districtCode': locationValue.length >= 3 ? locationValue[2] : "", 'districtName': location.value != "" ? location.value.split("-")[2] : "", "educationCode": educationList[educationSelect.value].value, "height": heightSelect.value != -1 ? heightList[heightSelect.value] : "", 'hometownProvinceCode': homeLocationValue.length >= 2 ? homeLocationValue[0] : "", 'hometownProvinceName': homeLocation.value != "" ? homeLocation.value.split("-")[0] : "", 'hometownCityCode': homeLocationValue.length >= 2 ? homeLocationValue[1] : "", 'hometownCityName': homeLocation.value != "" ? homeLocation.value.split("-")[1] : "", "incomeCode": incomeSelect.value != -1 ? incomeList[incomeSelect.value].value : "", "maritalStatusCode": maritalSelect.value != -1 ? maritalList[maritalSelect.value].value : "", "nickName": userData.value?.nickName ?? "", 'occupation': occupation.value != "" ? occupation.value.split("-")[1] : "", 'occupationCode': occupationValue.length >= 2 ? occupationValue[1] : "", "propertyPermitsCode": propertySelect.value != -1 ? propertyList[propertySelect.value].value : "", }; final response = await _userApi.editOwnMarriageInformation(payload); if (response.data.isSuccess) { SmartDialog.showToast('保存成功'); final result = await _userApi.getMarriageInformationDetail(); // print(result.data); if (result.data.isSuccess) { final information = result.data.data!; information.matchmakerFlag = userData.value?.matchmakerFlag ?? false; information.realName = userData.value?.realName; information.phone = userData.value?.phone; GlobalData().userData = information; await storage.write('userId', GlobalData().userId); } } else{ SmartDialog.showToast(response.data.message); return; } } catch (e) { print('资料提交审核失败: $e'); SmartDialog.showToast('资料提交审核失败,请重试'); return; } } }