You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

780 lines
25 KiB

import 'dart:async';
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 birthday = ''.obs;
final message = ''.obs;
final realDescribe = ''.obs;
final messageController = TextEditingController().obs;
final name = ''.obs;
final nameController = TextEditingController().obs;
// 选择日期
void selectBirthday(String selectedDate) {
birthday.value = selectedDate;
saveData();
// 打印选择的日期
print('选择的出生日期: $selectedDate');
// 显示选择结果
// SmartDialog.showToast('出生日期已选择');
}
final nowSelect = 0.obs;
List<String> 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 = <EducationData>[].obs;
final incomeList = <EducationData>[].obs;
final maritalList = <EducationData>[].obs;
final propertyList = <EducationData>[].obs;
final occupationList = <OccupationData>[].obs;
final occupationShowData = {}.obs;
final areaShowData = {}.obs;
final avatarUrl = ''.obs;
// 本地选择的头像文件路径(提交时先上传)
final avatarLocalPath = ''.obs;
final imgList = <String>[].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();
final ImagePickerPlatform imagePickerImplementation =
ImagePickerPlatform.instance;
if (imagePickerImplementation is ImagePickerAndroid) {
imagePickerImplementation.useAndroidPhotoPicker = true;
}
_userApi = Get.find<UserApi>();
getBaseData();
}
getBaseData() async {
await getInfo();
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];
}
birthday.value = userData.value?.birthDate ?? "";
message.value = (userData.value?.auditDescribeInfo != null && userData.value?.auditDescribeInfo != "") ? (userData.value?.auditDescribeInfo ?? "") : (userData.value?.describeInfo ?? "");
realDescribe.value = message.value;
messageController.value.value = TextEditingValue(
text: message.value,
selection: TextSelection.fromPosition(TextPosition(offset: message.value.length)),
);
name.value = userData.value?.nickName ?? "";
nameController.value.value = TextEditingValue(
text: name.value,
selection: TextSelection.fromPosition(TextPosition(offset: name.value.length)),
);
}
goPreview() {
Get.to(() => UserInformationPage(miId: userData.value?.id ?? "", userId: GlobalData().userId ?? ""));
}
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<void> 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<void> 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<void> 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<XFile>? image = await picker.pickMultiImage(limit: 9 - imgList.length);
print(image);
if (image != null && image.isNotEmpty) {
final futures = image.map((e){
return processSelectedMoreImage(File(e.path), type);;
});
final list = await Future.wait(futures);
imgList.addAll(list);
print(imgList);
SmartDialog.dismiss();
SmartDialog.showToast('上传相册成功');
savaImgList();
// for(int i = 0; i<image.length; i++){
//
// await processSelectedMoreImage(File(image[i].path), type);
// if(i == image.length - 1){
//
// SmartDialog.dismiss();
// SmartDialog.showToast('上传相册成功');
//
// savaImgList();
// }
// }
}
} catch (e) {
print('选择图片失败: $e');
// 更友好的错误提示
if (e.toString().contains('permission') || e.toString().contains('权限')) {
SmartDialog.showToast('相册权限被拒绝,请在设置中允许访问相册');
} else {
SmartDialog.showToast('选择图片失败,请重试');
}
}
}
// 通用权限申请
Future<bool> _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<void> 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<String> processSelectedMoreImage(File imageFile, int type) async {
try {
// 显示加载提示
SmartDialog.showLoading(msg: '上传相册中...');
String objectName = '${DateUtil.getNowDateMs()}.${imageFile.path.split('.').last}';
String imageUrl = await OSSManager.instance.uploadFile(imageFile.readAsBytesSync(), objectName);
print('上传成功,图片URL: $imageUrl');
return imageUrl;
} catch (e) {
SmartDialog.dismiss();
print('处理图片失败: $e');
SmartDialog.showToast('上传相册失败,请重试');
return "";
}
}
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) {
userData.value?.auditProfilePhoto = {
"auditStatus": 0
};
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(avatarAuditResp.data.message);
return;
}
} catch(e){
print('头像提交审核失败: $e');
SmartDialog.showToast('头像提交审核失败,请重试');
return;
}
}
savaImgList() async {
try{
final originImg = userData.value!.photoList!.map((e) => e.photoUrl).toSet();
final result = imgList
.where((e) => !originImg.contains(e))
.toList();
final imgPayload = {
'miId': userData.value?.id ?? 0,
'authenticationCode': '6',
'value': '0',
'imgUrl': result.isNotEmpty ? result : ['0'],
};
final imgAuditResp = await _userApi.saveCertificationAudit(imgPayload);
if (imgAuditResp.data.isSuccess) {
getInfo();
} else{
SmartDialog.showToast(imgAuditResp.data.message);
return;
}
} catch(e){
print('相册提交审核失败: $e');
SmartDialog.showToast('相册提交审核失败,请重试');
return;
}
}
savaDescribeInfo() async {
try{
final originImg = userData.value!.photoList!.map((e) => e.photoUrl).toSet();
final result = imgList
.where((e) => !originImg.contains(e))
.toList();
final imgPayload = {
'miId': userData.value?.id ?? 0,
'authenticationCode': '7',
'value': message.value,
'imgUrl': ['0'],
};
final imgAuditResp = await _userApi.saveCertificationAudit(imgPayload);
if (imgAuditResp.data.isSuccess) {
realDescribe.value = message.value;
getInfo();
SmartDialog.showToast("交友心声已提交审核");
Get.back();
} else{
SmartDialog.showToast(imgAuditResp.data.message);
return;
}
} catch(e){
print('相册提交审核失败: $e');
SmartDialog.showToast('交友心声提交审核失败,请重试');
return;
}
}
getInfo() async {
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;
userData.value = GlobalData().userData;
await storage.write('userId', GlobalData().userId);
setData();
}
}
deleteImgList(int index) async {
if(userData.value!.photoList!.length > index){
try {
final avatarPayload = {
'miId': userData.value!.photoList![index].miId,
'id': userData.value!.photoList![index].id,
'photoUrl': userData.value!.photoList![index].photoUrl,
};
final res = await _userApi.userDelPhotos(avatarPayload);
if (res.data.isSuccess) {
imgList.removeAt(index);
userData.value!.photoList!.removeAt(index);
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(res.data.message);
return;
}
} catch(e){
print('图片删除失败: $e');
SmartDialog.showToast('图片删除失败,请重试');
return;
}
} else {
imgList.removeAt(index);
}
}
Timer? _debounce;
void onTextChanged(String text) {
// 取消上一次的计时
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 500), () {
name.value = text;
saveData();
});
}
saveData() async {
try {
final payload = {
'birthDate': birthday.value,
'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": educationSelect.value != -1 ? 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": name.value,
'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;
}
}
}