circle_app/circle_app/lib/util/util.dart
2024-05-16 18:20:37 +08:00

1316 lines
41 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:app_settings/app_settings.dart';
import 'package:circle_app/app/chat/view.dart';
import 'package:circle_app/app/circle/view.dart';
import 'package:circle_app/app/circle/widgets/discover.dart';
import 'package:circle_app/app/userinfo/logic.dart';
import 'package:circle_app/common/Widgets/base_tip_widget.dart';
import 'package:circle_app/common/values/values.dart';
import 'package:circle_app/main.dart';
import 'package:circle_app/network/api.dart';
import 'package:circle_app/router/app_routers.dart';
import 'package:circle_app/util/eventBus.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_conversation_view_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:video_compress/video_compress.dart';
import '../app/circle/logic.dart';
import '../app/home/logic.dart';
import '../app/select_circle/logic.dart';
import '../common/Widgets/open_vip_tip/view.dart';
import '../common/Widgets/wx_edit_dialog.dart';
import '../common/colors/app_color.dart';
import '../network/dio_manager.dart';
import 'SharedPreferencesHelper.dart';
List chatIdList = [];
class Util {}
//获取图片
String getBaseImage(String image) {
return '${Values.base_images}${image}.png';
}
String getHomeImage(String image) {
return '${Values.home_images}${image}.png';
}
String getDisCoverImage(String image) {
return '${Values.discover_images}${image}.png';
}
String getLoginImage(String image) {
return '${Values.login_images}${image}.png';
}
String getMineImage(String image) {
return '${Values.mine_images}${image}.png';
}
String getMsgImage(String image) {
return '${Values.msg_images}${image}.png';
}
String getNavigatorImage(String image) {
return '${Values.navigator_images}${image}.png';
}
String getTabbarImage(String image) {
return '${Values.tabbar_images}${image}.png';
}
String getCircleImage(String image) {
return '${Values.circle_images}${image}.png';
}
///弹窗文本提示 msg: 提示内容
showOKToast(String msg) {
showToast(
msg,
duration: Duration(seconds: msg.length > 15 ? 5 : msg.length > 10 ? 3 : 2),
position: ToastPosition.center,
backgroundColor: Colors.black,
radius: 13.0,
textStyle: const TextStyle(fontSize: 16.0,color: Colors.white),
);
}
loaddingWidget(bool isMore,{String tip = '--到底了--'}) {
return Container(
alignment: Alignment.center,
child: isMore
? const CircularProgressIndicator(
color: Color(0xFF07FAFB),
)
: Container(
margin: EdgeInsets.only(top: 4.sp, bottom: 4.sp),
child: Text(
tip,
style: TextStyle(color: Colors.white, fontSize: 13.sp),
),
),
);
}
noResultWidget({String tip = '正在等待被填充~',Function? callBack, String action = '重新加载'}) {
return Container(
width: Get.width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
getBaseImage('no_result'),
width: 200.sp,
),
SizedBox(
height: 8.sp,
),
if (callBack == null || tip.isNotEmpty)
Text(
tip,
style: TextStyle(color: Color(0xffdbdbdb), fontSize: 15.sp),
),
if (callBack != null)
GestureDetector(
onTap: () {
callBack();
},
child: Container(
margin: EdgeInsets.only(top: 10.sp),
height: 42.sp,
width: 160.sp,
alignment: Alignment.center,
// padding: EdgeInsets.only(left: 4.sp,right: 4.sp),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.sp),
gradient: AppColor.mainVerLinearGradient),
child: Text(
action,
style: TextStyle(color: Colors.white, fontSize: 14.sp),
),
),
)
],
),
);
}
///value: 文本内容fontSize : 文字的大小fontWeight文字权重maxWidth文本框的最大宽度maxLines文本支持最大多少行
double calculateTextHeight(String value, fontSize, FontWeight fontWeight,
double maxWidth, int maxLines) {
value = filterText(value);
TextPainter painter = TextPainter(
///AUTO华为手机如果不指定locale的时候该方法算出来的文字高度是比系统计算偏小的。
locale: WidgetsBinding.instance.window.locale,
maxLines: maxLines,
textDirection: TextDirection.ltr,
textScaleFactor: 1,
//字体缩放大小
text: TextSpan(
text: value,
style: TextStyle(
fontWeight: fontWeight,
fontSize: fontSize,
)));
painter.layout(maxWidth: maxWidth);
///文字的宽度:painter.width
return painter.height;
}
String filterText(String text) {
String tag = '<br>';
while (text.contains('<br>')) {
// flutter 算高度,单个\n算不准,必须加两个
text = text.replaceAll(tag, '\n\n');
}
return text;
}
String convertToTenThousand(int number) {
if (number >= 10000) {
double result = number / 10000;
return '${result.toStringAsFixed(1)}';
} else {
return number.toString();
}
}
pushLoginPage() async {
await logoutIM();
SharedPreferencesHelper.getInstance().then((sharedPreferences) {
String loginPhone =
sharedPreferences.getString(SharedPreferencesHelper.LOGINPHONE) ?? "";
String pwd =
sharedPreferences.getString(SharedPreferencesHelper.PWD) ?? "";
print(loginPhone);
List<String> tipList = sharedPreferences.getStringList();
sharedPreferences.clear();
sharedPreferences.setString(SharedPreferencesHelper.LOGINPHONE, loginPhone);
sharedPreferences.setString(SharedPreferencesHelper.PWD, pwd);
sharedPreferences.setBool(SharedPreferencesHelper.AGREEMENT, true);
sharedPreferences.setString(SharedPreferencesHelper.firstLogin, '1');
sharedPreferences.setStringList(tipList);
});
if (AppRoutes.Login != Get.currentRoute) {
Get.offAllNamed(AppRoutes.Login);
}
}
String filterSensitiveWords(String input, List<String> sensitiveWords) {
String filteredString = input;
for (String word in sensitiveWords) {
String replacement = '*' * word.length;
filteredString = filteredString.replaceAll(word, replacement);
}
return filteredString;
}
String getAgeCOntent(int gender, int age, int role, int orientation) {
return "${getGenderContent(gender)}·${age}·${getRoleContent(role)}·${getOrientationContent(orientation)}";
}
late ConfigBean configBean;
List<MyConfigData> numbers = [];
List<String> genderList = [];
List<String> orientationList = [];
List<String> roleList = [];
String getGenderContent(int number) {
if (number == null) return '';
if (genderList.length != 0) {
return genderList[number - 1];
} else {
switch (number) {
case 1:
return "";
case 2:
return "";
case 3:
return "MTF";
case 4:
return "FTM";
case 5:
return "CD";
case 6:
return "酷儿";
default:
return "";
}
}
}
String getOrientationContent(int number) {
if (orientationList.length != 0) {
return orientationList[number - 1];
} else {
switch (number) {
case 1:
return "异性恋";
case 2:
return "同性恋";
case 3:
return "双性恋";
case 4:
return "泛性恋";
case 5:
return "无性恋";
case 6:
return "智性恋";
case 7:
return "性单恋";
default:
return "";
}
}
}
String getRoleContent(int number) {
if (roleList.length != 0) {
return roleList[number - 1];
} else {
switch (number) {
case 1:
return "Sado";
case 2:
return "Maso";
case 3:
return "Dom";
case 4:
return "Sub";
case 5:
return "Switch";
default:
return "";
}
}
}
typedef void MyCallback(String path);
Future<void> compressVideo(
String inputPath, String outputPath, MyCallback myCallback) async {
final info = await VideoCompress.compressVideo(
inputPath,
quality: VideoQuality.MediumQuality,
deleteOrigin: false,
);
if (info != null && null != info.path) {
print(info.path);
myCallback(info.path!);
} else {
print('视频压缩失败');
}
}
class CustomRefreshHeader extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ClassicHeader(
// 自定义刷新时的文字
refreshingText: "正在刷新...",
idleText: "下拉刷新",
completeText: "刷新完成",
failedText: "刷新失败",
);
}
}
class CustomLoadFooter extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ClassicFooter(
// 自定义加载更多时的文字
canLoadingText: "松手开始加载数据",
loadingText: "正在加载...",
idleText: "上拉加载更多",
noDataText: "到底了~",
failedText: "加载失败",
);
}
}
class DiyLoadFooter extends StatefulWidget {
String noDataText;
DiyLoadFooter({super.key,required this.noDataText});
@override
State<DiyLoadFooter> createState() => _DiyLoadFooterState();
}
class _DiyLoadFooterState extends State<DiyLoadFooter> {
@override
Widget build(BuildContext context) {
return ClassicFooter(
// 自定义加载更多时的文字
canLoadingText: "松手开始加载数据",
loadingText: "正在加载...",
idleText: "上拉加载更多",
noDataText: widget.noDataText,
failedText: "加载失败",
);
}
}
class CustomLikeLoadFooter extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ClassicFooter(
// 自定义加载更多时的文字
canLoadingText: "松手开始加载数据",
loadingText: "正在加载...",
idleText: "上拉加载更多",
noDataText: "",
height: 20.sp,
spacing: 5,
failedText: "加载失败",
);
}
}
// 获取应用程序的文档目录路径
Future<String> getApplicationDocumentsDirectoryPath() async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
// 获取应用程序的支持目录路径
Future<String> getApplicationSupportDirectoryPath() async {
final directory = await getApplicationSupportDirectory();
return directory.path;
}
// 获取临时目录路径
Future<String> getTemporaryDirectoryPath() async {
final directory = await getTemporaryDirectory();
return directory.path;
}
// 获取库目录路径
Future<String> getLibraryDirectoryPath() async {
final directory = await getLibraryDirectory();
return directory.path;
}
//跳转到文明公约
void navigateToCodeOfConduct() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "文明公约",
"url": "https://docs.qq.com/doc/DZUtoZ3V0S3ltY2Zw"
});
}
//跳转到用户协议
void navigateToUserAgreement() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "用户协议",
"url": Platform.isIOS
? "https://docs.qq.com/doc/DZVV1SkttZGlPUW1H"
: "https://iquanpai.com/app-h5/4_163.html"
});
}
//跳转到如何上精选
void navigateToQueen() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "如何上精选",
"url": 'https://iquanpai.com/app-h5/4_184.html'
});
}
//跳转到隐私政策
void navigateToPrivacyPolicy() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "隐私协议",
"url": Platform.isIOS
? "https://docs.qq.com/doc/DZXhvcXV6b1RNTUx1"
: "https://iquanpai.com/app-h5/4_164.html"
});
}
//发布内容规范
void navigateToContentGuidelines() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "发布内容规范",
"url": Platform.isIOS
? "https://docs.qq.com/doc/DZVhLamZDQnJ0eHds"
: "https://iquanpai.com/app-h5/4_165.html"
});
}
//合伙人协议
void navigateToPartnerAgreement() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "合伙人协议",
"url": Platform.isIOS
? "https://docs.qq.com/doc/DZUpwWFdNcGlsYld4"
: "https://iquanpai.com/app-h5/4_166.html"
});
}
//小票充值协议
void navigateToItem() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "小票充值协议",
"url":'https://www.iquanpai.com/app-h5/4_173.html'
});
}
//邀请攻略
void navigateToInviteStrategy() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "邀请攻略",
"url": "https://leyuan666.com/app-h5/4_168.html"
});
}
//跳转到赚钱攻略
navigateStartGetMoeny() {
Get.toNamed(AppRoutes.WebViewActivity, arguments: {
'title': "微乐园赚钱攻略",
"url": 'https://iquanpai.com/app-h5/4_178.html'
});
}
void navigateToCustomRoute(BannerItem bannerItem) async {
print(bannerItem.param);
switch (bannerItem.type) {
case 1:
if (bannerItem.scene == 'internal') {
Get.toNamed(AppRoutes.WebViewActivity,
arguments: {'title': "", "url": bannerItem.param.toString()});
} else {
await launch(bannerItem.param.toString(),forceSafariVC: false);
}
break;
case 2:
switch (bannerItem.scene) {
case "scene_2":
List<MyConfigData> numbers = [];
if (bannerItem.param!.isNotEmpty) {
String paramJson = bannerItem.param.toString();
paramJson = paramJson.replaceAll(r'\', ''); // 去除反斜杠转义
Map<String, dynamic> jsonData = json.decode(paramJson);
numbers.add(MyConfigData(
jsonData['id'].toString(), jsonData['name'], false));
}
Get.toNamed(AppRoutes.Call_out, arguments: {'numbers': numbers});
break;
case "scene_3":
Get.toNamed(AppRoutes.FeedbackActivity);
break;
}
break;
case 3:
switch (bannerItem.scene) {
case "scene_1":
Get.toNamed(AppRoutes.Invite);
break;
case "scene_4":
if (bannerItem.param!.isEmpty) {
Get.toNamed(AppRoutes.UserInfoActivity);
} else {
Get.toNamed(AppRoutes.UserInfoActivity,
arguments: bannerItem.param.toString());
}
break;
}
break;
}
}
unLockWxSuccessResult(String userId) {
String currentRoute = Get.currentRoute;
if (currentRoute == AppRoutes.Home) {
EventBusManager.fire(DiscoverDataRefresh(userId));
} else if (currentRoute == AppRoutes.UserInfoActivity) {
var logic = Get.find<UserinfoLogic>();
logic.fetchUserInfo("${Api.getUserInfoTA + userId}/home");
} else if (currentRoute == AppRoutes.Chat) {
EventBusManager.fire(ChatLoadUserInfoData());
}
}
Size boundingTextSize(BuildContext context, String text, TextStyle style,
{int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
if (text == null || text.isEmpty) {
return Size.zero;
}
final TextPainter textPainter = TextPainter(
textDirection: TextDirection.ltr,
locale: Localizations.localeOf(context),
text: TextSpan(text: text, style: style),
maxLines: maxLines)
..layout(maxWidth: maxWidth);
return textPainter.size;
}
//跳转发消息页面
pushChatPage(String userId, String imId, String userName) {
var con = V2TimConversation(
conversationID: "c2c_$imId", userID: imId, showName: userName, type: 1);
Get.toNamed(AppRoutes.Chat, arguments: con);
createCustomMsg(userId, imId);
}
createCustomMsg(String userId, String imId) async {
if (chatIdList.contains(imId)) return;
chatIdList.add(imId);
//通过会话ID获取指定会话列表
V2TimValueCallback<List<V2TimConversation>>
getConversationListByConversaionIdsRes = await TencentImSDKPlugin
.v2TIMManager
.getConversationManager()
.getConversationListByConversaionIds(
conversationIDList: ["c2c_$imId"]); //需要获取会话列表数据的会话id列表
if (getConversationListByConversaionIdsRes.code == 0 &&
getConversationListByConversaionIdsRes.data!.isEmpty) {
//获取资料,然后发送自定义卡片消息
var data = await DioManager.instance.get(
url: 'msg-service/user/$userId/chat/card',
);
if (data['code'] == 200) {
String desc = '';
String cityStr = '';
Map<String, dynamic> info = {};
// 对方喜欢了你100
// ·你们有共同喜欢的圈友90
// ·你喜欢的圈友也喜欢TA80
// ·你们都在深圳留下过足迹70
// ·你们有2个共同的圈子圈子名称、圈子名称60
// ·可能是你想认识的人50
// ·很多圈友都喜欢TA40
// ·TA是乐园优秀圈主哦30
var titleList = [];
var recommendCircleFriendData = data['data'];
if (data['data']['both_interests'] != null) {
List<dynamic> both_interests = data['data']['both_interests'];
List<String> circleList = [];
both_interests.forEach((element) {
circleList.add(element['title']);
});
if (circleList.isNotEmpty) {
info['both_interests'] =
'你们有${circleList.length}个共同的圈子:${circleList.join('')}';
if (desc.isEmpty) {
desc = '你们有${circleList.length}个共同的圈子:${circleList.join('')}';
}
}
}
if (data['data']['both_cities'] != null) {
List city = data['data']['both_cities'];
print('城市' + city.toString());
if (city.isNotEmpty) {
desc = '你们都在${city.first}留下过足迹';
cityStr = '你们都在${city.first}留下过足迹';
}
}
if (desc.isNotEmpty) {
if (data['data']['both_cities'] != null) {
info['city'] = cityStr;
}
info['title'] = recommendCircleFriendData;
info['interests'] = data['data']['interests'] ?? [];
info['my'] = data['data']['my'] ?? '';
info['myInterests'] = data['data']['myInterests'] ?? [];
info['user'] = data['data']['user'];
info['guide_text'] = data['data']['guide_text'] ?? '请问现在有空吗?';
await sendCustomMsg(imId, jsonEncode(info), desc);
return true;
}
}
}
return false;
}
//发送文本消息
sendTextMsg(String userId, {String content = '看看这次缘分匹配到哪位小可爱呢?'}) async {
// 创建文本消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createTextMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createTextMessage(
text: content, // 文本信息
);
if (createTextMessageRes.code == 0) {
// 文本信息创建成功
String? id = createTextMessageRes.data?.id;
// 发送文本消息
// 在sendMessage时若只填写receiver则发个人用户单聊消息
// 若只填写groupID则发群组消息
// 若填写了receiver与groupID则发群内的个人用户消息在群聊中显示只有指定receiver能看见
V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
.v2TIMManager
.getMessageManager()
.sendMessage(id: id!, receiver: userId, groupID: '');
if (sendMessageRes.code == 0) {
// 发送成功
return true;
}
return false;
}
// V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
// await TencentImSDKPlugin.v2TIMManager
// .getMessageManager()
// .createTextAtMessage(text: '看看这次缘分匹配到哪位小可爱呢?',atUserList: [],
// );
// if (createCustomMessageRes.code == 0) {
// String? id = createCustomMessageRes.data?.id;
// // 发送自定义消息
// // 在sendMessage时若只填写receiver则发个人用户单聊消息
// // 若只填写groupID则发群组消息
// // 若填写了receiver与groupID则发群内的个人用户消息在群聊中显示只有指定receiver能看见
// V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
// .v2TIMManager
// .getMessageManager()
// .sendMessage(id: id!, receiver: userId,groupID: '');
// if (sendMessageRes.code == 0) {
// // 发送成功
// return true;
// }
// }
}
//发送卡片自定义消息
sendCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'cardData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
// 发送自定义消息
// if (Get.currentRoute == AppRoutes.Chat) {
// EventBusManager.fire(SendCoustomMessage(createCustomMessageRes));
// } else {
V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
.v2TIMManager
.getMessageManager()
.sendMessage(id: id!, receiver: userId, groupID: '');
if (sendMessageRes.code == 0) {
// 发送成功
EventBusManager.fire(ChatRefreshMsg());
sendMessageRes.data?.customElem?.data; //自定义data
sendMessageRes.data?.customElem?.desc; //自定义desc
sendMessageRes.data?.customElem?.extension; //自定义extension
}
// }
}
}
//发送用户主页自定义消息
sendUserHomeCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'userHomeData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
.v2TIMManager
.getMessageManager()
.sendMessage(id: id!, receiver: userId, groupID: '');
if (sendMessageRes.code == 0) {
// 发送成功
showOKToast('发送成功');
sendMessageRes.data?.customElem?.data; //自定义data
sendMessageRes.data?.customElem?.desc; //自定义desc
sendMessageRes.data?.customElem?.extension; //自定义extension
}
}
}
//发送圈子自定义消息
sendCircleCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'circleData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
if (Get.currentRoute == AppRoutes.Chat) {
EventBusManager.fire(SendCoustomMessage(createCustomMessageRes));
} else {
V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
.v2TIMManager
.getMessageManager()
.sendMessage(id: id!, receiver: userId, groupID: '');
if (sendMessageRes.code == 0) {
// 发送成功
showOKToast('发送成功');
sendMessageRes.data?.customElem?.data; //自定义data
sendMessageRes.data?.customElem?.desc; //自定义desc
sendMessageRes.data?.customElem?.extension; //自定义extension
}
}
}
}
//发送求送礼物自定义消息
sendGetGiftCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'getGiftData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
// 发送自定义消息
EventBusManager.fire(SendCoustomMessage(createCustomMessageRes));
}
}
//发送许愿自定义消息
sendGetWishCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'getWishData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
// 发送自定义消息
EventBusManager.fire(SendCoustomMessage(createCustomMessageRes));
//
// // 在sendMessage时若只填写receiver则发个人用户单聊消息
// // 若只填写groupID则发群组消息
// // 若填写了receiver与groupID则发群内的个人用户消息在群聊中显示只有指定receiver能看见
// V2TimValueCallback<V2TimMessage> sendMessageRes = await TencentImSDKPlugin
// .v2TIMManager
// .getMessageManager()
// .sendMessage(id: id!, receiver: userId, groupID: '');
// if (sendMessageRes.code == 0) {
// // 发送成功
// sendMessageRes.data?.customElem?.data; //自定义data
// sendMessageRes.data?.customElem?.desc; //自定义desc
// sendMessageRes.data?.customElem?.extension; //自定义extension
// showOKToast('发送成功');
// }
}
}
//发送邀请许愿自定义消息
sendInventWishCustomMsg(String userId, String data, String desc) async {
// 创建自定义消息
V2TimValueCallback<V2TimMsgCreateInfoResult> createCustomMessageRes =
await TencentImSDKPlugin.v2TIMManager
.getMessageManager()
.createCustomMessage(
data: data,
desc: desc,
extension: 'getInventWishData',
);
if (createCustomMessageRes.code == 0) {
String? id = createCustomMessageRes.data?.id;
// 发送自定义消息
EventBusManager.fire(SendCoustomMessage(createCustomMessageRes));
}
}
//判断卡片返回信息
Map checkCardReturnData(Map recommendCircleFriendData) {
var titleList = [];
Map info = {};
if (recommendCircleFriendData['is_follow_me']) {
titleList.add('对方喜欢了你');
} else if (recommendCircleFriendData['has_both_friend']) {
titleList.add('你们有共同喜欢的圈友');
} else if (recommendCircleFriendData['has_friend_follow_to']) {
titleList.add('你喜欢的圈友也喜欢TA');
}
if (titleList.length < 3) {
List citys = recommendCircleFriendData['both_cities'];
if (citys.isNotEmpty) {
titleList.add('你们都在${citys.first}留下过足迹');
}
}
if (titleList.length < 3) {
List circles = recommendCircleFriendData['both_interests'];
if (circles.isNotEmpty) {
List<dynamic> both_interests =
recommendCircleFriendData['both_interests'];
List<String> circleList = [];
both_interests.forEach((element) {
circleList.add(element['title']);
});
if (circleList.isNotEmpty) {
titleList
.add('你们有${circleList.length}个共同的圈子:${circleList.join('')}');
}
}
}
if (titleList.length < 3) {
if (recommendCircleFriendData.containsKey('is_new_user')) {
titleList.add('我刚来到这里哦');
}
}
if (titleList.length < 3) {
if (recommendCircleFriendData['is_wanna_meet']) {
titleList.add('很多圈友都喜欢TA');
}
}
if (titleList.length < 3) {
if (recommendCircleFriendData['is_most_fans']) {
titleList.add('可能是你想认识的人');
}
}
if (titleList.length < 3) {
if (recommendCircleFriendData['is_excellent_qz_leader']) {
titleList.add('TA是乐园优秀圈主哦');
}
}
if (titleList.length >= 1) {
info['city'] = titleList.first;
}
if (titleList.length >= 2) {
info['both_interests'] = titleList[1];
}
if (titleList.length >= 3) {
info['desc'] = titleList[2];
}
return info;
}
Future<List<V2TimUserFullInfo>> loadConverstationListData() async {
TUIConversationViewModel model =
serviceLocator<TUIConversationViewModel>();
List<V2TimConversation?> filteredConversationList = model.conversationList
.where(
(element) => (element?.groupID != null || element?.userID != null))
.toList();
// 过滤指定的 userID qpqz_prod_10_10000000000
String devtTargetUserID = "qpqz_dev_10_10000000000";
String prodTargetUserID = "qpqz_prod_10_10000000000";
filteredConversationList = filteredConversationList
.where((conversation) =>
conversation?.userID != devtTargetUserID &&
conversation?.userID != prodTargetUserID)
.toList();
List<String> userIdList = [];
filteredConversationList.forEach((element) {
userIdList.add(element!.userID!);
});
V2TimValueCallback<String> getLoginUserRes =
await TencentImSDKPlugin.v2TIMManager.getLoginUser();
if (getLoginUserRes.code == 0) {
//获取成功
if (getLoginUserRes.data != null) {
userIdList.insert(
0, getLoginUserRes.data!); // getLoginUserRes.data为查询到的登录用户的UserID
}
}
//获取用户资料
V2TimValueCallback<List<V2TimUserFullInfo>> getUsersInfoRes =
await TencentImSDKPlugin.v2TIMManager
.getUsersInfo(userIDList: userIdList); //需要查询的用户id列表
if (getUsersInfoRes.code == 0) {
// 查询成功
getUsersInfoRes.data?.forEach((element) {
element.allowType; //用户的好友验证方式 0:允许所有人加我好友 1:不允许所有人加我好友 2:加我好友需我确认
element.birthday; //用户生日
element.customInfo; //用户的自定义状态
element.faceUrl; //用户头像 url
element.gender; //用户的性别 1:男 2:女
element.level; //用户的等级
element.nickName; //用户昵称
element.role; //用户的角色
element.selfSignature; //用户的签名
element.userID; //用户 ID
});
return getUsersInfoRes.data ?? [];
}
return [];
}
showVipDialog() {
Get.bottomSheet(
Scaffold(
backgroundColor: Colors.transparent,
body: Open_vip_tipPage(false),
),
isScrollControlled: true,
enableDrag: false).then((value) {
});
}
locationDialog() {
Get.bottomSheet(CupertinoAlertDialog(
content:
SingleChildScrollView(
child: ListBody(
children: <Widget>[Text("请开启位置权限用于寻找附近用户")],
),
),
actions: <Widget>[
CupertinoDialogAction(
child: Text("确定"),
onPressed: (){
Get.back();
AppSettings.openAppSettings();
},
),
CupertinoDialogAction(
child: Text("取消"),
onPressed: (){
Get.back();
},
),
],
),isScrollControlled: true,
enableDrag: false
);
}
Future<bool> checkPhotosStatus() async {
var status = await Permission.photos.status;
if (PermissionStatus.permanentlyDenied == status) {
Get.bottomSheet(CupertinoAlertDialog(
content:
SingleChildScrollView(
child: ListBody(
children: <Widget>[Text("请开启相册权限以上传图片/视频")],
),
),
actions: <Widget>[
CupertinoDialogAction(
child: Text("确定"),
onPressed: (){
AppSettings.openAppSettings();
},
),
CupertinoDialogAction(
child: Text("取消"),
onPressed: (){
Get.back();
},
),
],
),isScrollControlled: true,
enableDrag: false
);
}
return PermissionStatus.permanentlyDenied == status;
}
pushPage(String action,String param,{String name = ''}) {
// public final static String MY_MAIN = "my_main";//我的主页
// public final static String MY_USER_HOME = "my_user_home";//我的个人主页
// public final static String TO_USER_HOME = "to_user_home";//他人用户主页
// public final static String MY_GIFT_HALL = "my_gift_hall";//礼物馆
// public final static String TO_GIFT_HALL = "to_gift_hall";//他人礼物馆
// public final static String USER_HOME_CALLOUT = "user_home_callout";//个人主页喊话栏目
// public final static String CHAT = "chat";//私聊
// public final static String STORY_PERSONAGE = "story_personage";//故事达人
// public final static String FIND_PAGE = "find_page";//发现栏目
// public final static String CUSTOM_SERVICE = "custom_service";//客服
// public final static String INVITE = "invite";//邀请页
// public final static String WALLET = "wallet";//个人资产/钱包
// public final static String OFFSITE_SHARE = "offsite_share";//站外分享
// public final static String GOOD_RATE = "good_rate";//好评反馈
// public final static String BUY_VIP = "buy_vip";//购买会员
// public final static String RECHARGE = "recharge";//充值
// public final static String INTEREST = "interest";//圈子
// public final static String GOOD_AUTH = "good_auth";//good认证
if (action == 'my_main') {
Get.until((route) => route.settings.name == '/home');
final homeLogic = Get.put(HomeLogic());
homeLogic.tabController.animateTo(3);
homeLogic.updateIndex(3);
} else if (action == 'my_user_home') {
Get.toNamed(AppRoutes.UserInfoActivity);
} else if (action == 'find_page') {
Get.until((route) => route.settings.name == '/home');
final homeLogic = Get.put(HomeLogic());
homeLogic.tabController.animateTo(0);
homeLogic.updateIndex(0);
Future.delayed(Duration(milliseconds: 200),() {
EventBusManager.fire(ChangeIndex(2));
});
} else if (action == 'to_user_home' || action == 'user_home_callout') {
Get.toNamed(AppRoutes.UserInfoActivity,arguments: param);
} else if (action == 'my_gift_hall') {
Get.toNamed(AppRoutes.GiftShopPage,arguments: '');
} else if (action == 'to_gift_hall') {
Get.toNamed(AppRoutes.GiftShopPage,arguments: param);
} else if (action == 'invite') {
Get.toNamed(AppRoutes.Invite);
} else if (action == 'wallet') {
Get.toNamed(AppRoutes.MyAssets);
} else if (action == 'offsite_share') {
Get.toNamed(AppRoutes.ExternalsharePage);
} else if (action == 'good_rate') {
if (Platform.isAndroid) {
Get.toNamed(AppRoutes.Good_Reviews);
} else {
launch('https://apps.apple.com/cn/app/%E5%BE%AE%E4%B9%90%E5%9B%AD-%E4%BA%9A%E6%96%87%E5%8C%96%E5%A4%9A%E5%85%83%E4%BA%A4%E5%8F%8B%E5%9F%BA%E5%9C%B0/id6459449499', forceSafariVC: false);
}
} else if (action == 'buy_vip') {
showOepnVipDialog();
} else if (action == 'recharge') {
showRechargeScreenDialog();
} else if (action == 'chat') {
pushChatPage(param.split('_').last, param, name);
} else if (action == 'custom_service') {
var con;
if(kDebugMode){
con = V2TimConversation(
conversationID: "c2c_qpqz_dev_10_102", userID: "qpqz_dev_10_102", showName: "测试乐园客服", type: 1);
}else{
con = V2TimConversation(
conversationID: "c2c_qpqz_prod_10_102", userID: "qpqz_prod_10_102", showName: "乐园客服", type: 1);
}
Get.toNamed(AppRoutes.Chat, arguments: con);
} else if(action == 'interest') {
Get.toNamed(AppRoutes.Signal_circle_list,arguments: param);
} else if(action == 'good_auth') {
var con;
if(kDebugMode){
con = V2TimConversation(
conversationID: "c2c_qpqz_dev_10_102", userID: "qpqz_dev_10_102", showName: "测试乐园客服", type: 1);
}else{
con = V2TimConversation(
conversationID: "c2c_qpqz_prod_10_102", userID: "qpqz_prod_10_102", showName: "乐园客服", type: 1);
}
Get.toNamed(AppRoutes.Chat, arguments: con);
DioManager.instance.post(url: Api.goodAuth);
} else if (action == 'apply_interest_agent') {
sendApplyToAgentData(param);
}
}
void sendApplyToAgentData(var circleId) async {
var data = await DioManager.instance
.post(url: Api.applyToAgent + '$circleId');
if (data['code'] == 200) {
var con;
if(kDebugMode){
con = V2TimConversation(
conversationID: "c2c_qpqz_dev_10_102", userID: "qpqz_dev_10_102", showName: "测试乐园客服", type: 1);
}else{
con = V2TimConversation(
conversationID: "c2c_qpqz_prod_10_102", userID: "qpqz_prod_10_102", showName: "乐园客服", type: 1);
}
Get.toNamed(AppRoutes.Chat, arguments: con);
} else if (data['code'] == 32104) {
showReportDialog(Get.context!,data['msg']);
}
}
void showReportDialog(BuildContext context,String msg) {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
backgroundColor: Colors.transparent,
child: Container(
height: 200.sp,
padding: const EdgeInsets.all(1.0),
child: Stack(
children: [
Container(
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: AppColor.bgColor,
borderRadius: BorderRadius.circular(12.0.sp),
// gradient: const LinearGradient(
// colors: [Color(0xFFDD3DF4), Color(0xFF30FFD9)],
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
// ),
),
),
// Container(
// margin: EdgeInsets.all(1.sp),
// child: Image.asset(getMineImage("im_neglect"),fit: BoxFit.fill,),
// ),
Container(
margin: EdgeInsets.only(top: 12.sp),
child: Column(
children: [
Center(
child: Text(
"申请代理提示",
style:
TextStyle(color: Colors.white, fontSize: 16.sp),
),
),
Container(
margin: EdgeInsets.only(
top: 12.sp, left: 14.sp, right: 14.sp),
alignment: Alignment.center,
child: Text(
msg,
textAlign: TextAlign.left,
style: TextStyle(
color: const Color(0xCCF7FAFA), fontSize: 16.sp),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
Get.back();
Get.toNamed(AppRoutes.Invite);
},
child: Container(
margin: EdgeInsets.only(top: 16.sp),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(17),
gradient: const LinearGradient(
colors: [
Color(0x26FFFFFF),
Color(0x26FFFFFF),
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
),
padding: EdgeInsets.only(
top: 10.sp,
bottom: 10.sp,
left: 52.sp,
right: 52.sp),
child: const Text(
"前往邀请",
style: TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
)
],
)
],
),
)
],
),
),
);
},
);
}
Future<Position> getCurrentPosition() async {
return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
}
Future showUpdateWxPicker({String phone = ''}) {
return Get.bottomSheet(WxEditDialog(phone),isScrollControlled: true,enableDrag: false);
}
bool isValidQQ(String qq) {
String qqRegexp = r'^[1-9][0-9]{4,10}$';
RegExp regExp = RegExp(qqRegexp);
return regExp.hasMatch(qq);
}
checkMyUserStatus() async {
var data = await DioManager.instance.get(url: Api.getUserInfo);
if (data['code'] == 200) {
// UserInfoModel model = UserInfoModel.fromJson(data['data']);
// if (model.wxNum?.isNotEmpty ?? false) {
// showToast('已成功解锁TA的微信快去和TA私聊呗');
// } else {
// showToast('你已成功解锁TA的微信建议您也填写微信方便对方快速找到您哦');
// }
}
}