初始化提交

This commit is contained in:
2025-09-23 16:23:15 +08:00
commit 877b18a70f
590 changed files with 53617 additions and 0 deletions
@@ -0,0 +1,12 @@
import 'package:get/get.dart';
import '../../kr_home/controllers/kr_home_controller.dart';
import '../controllers/kr_statistics_controller.dart';
class KRStatisticsBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<KRHomeController>(() => KRHomeController());
Get.lazyPut<KRStatisticsController>(() => KRStatisticsController());
}
}
@@ -0,0 +1,229 @@
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_api.user.dart';
import '../../../common/app_run_data.dart';
import '../../../model/response/kr_user_online_duration.dart';
import '../../../modules/kr_home/controllers/kr_home_controller.dart';
import '../../../utils/kr_common_util.dart';
import '../../../utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:easy_refresh/easy_refresh.dart';
class KRStatisticsController extends GetxController {
/// VPN连接状态
final RxString kr_vpnStatus = ''.obs;
/// IP地址
final RxString kr_ipAddress = ''.obs;
/// 连接时间
final RxString kr_connectTime = ''.obs;
/// 协议类型
final RxString kr_protocol = ''.obs;
/// 当前连续记录(天)
final RxInt kr_currentStreak = 0.obs;
/// 最高记录(天)
final RxInt kr_highestStreak = 0.obs;
/// 最长连接时间(天)
final RxInt kr_longestConnection = 0.obs;
/// 每周保护时间数据
final RxList<double> kr_weeklyData = <double>[0, 0, 0, 0, 0, 0, 0].obs;
final RxBool kr_isConnected = false.obs;
late final KRHomeController kr_homeController;
/// 开始时间
final RxInt kr_startTime = 0.obs;
/// 结束时间
final RxInt kr_endTime = 0.obs;
/// 最后连接日期
final RxString kr_lastConnectDate = ''.obs;
final KRUserApi kr_userApi = KRUserApi();
final EasyRefreshController refreshController = EasyRefreshController(
controlFinishRefresh: true,
);
@override
void onInit() {
super.onInit();
kr_homeController = Get.find<KRHomeController>();
_kr_initializeListeners();
_kr_initializeValues();
kr_isConnected.value = kr_homeController.kr_isConnected.value;
ever(kr_homeController.kr_isConnected, (bool connected) {
kr_isConnected.value = connected;
});
ever(KRAppRunData.getInstance().kr_isLogin, (bool isLogin) {
if (!isLogin) {
kr_currentStreak.value = 0;
kr_longestConnection.value = 0;
kr_highestStreak.value = 0;
kr_weeklyData.value = <double>[0, 0, 0, 0, 0, 0, 0];
return;
}
kr_getUserSubscribeTrafficLogs();
});
}
/// 初始化监听器
void _kr_initializeListeners() {
ever(kr_homeController.kr_connectText, _kr_updateVpnStatus);
ever(kr_homeController.kr_currentIp, _kr_updateIpAddress);
ever(kr_homeController.kr_connectionTime, _kr_updateConnectionTime);
ever(kr_homeController.kr_currentProtocol, _kr_updateProtocol);
}
/// 初始化值
void _kr_initializeValues() {
kr_vpnStatus.value = kr_homeController.kr_connectText.value;
kr_ipAddress.value = kr_homeController.kr_currentIp.value;
kr_connectTime.value = kr_homeController.kr_connectionTime.value;
kr_protocol.value = kr_homeController.kr_currentProtocol.value;
// 这里可以添加其他统计数据的初始化
_kr_updateStatistics();
kr_getUserSubscribeTrafficLogs();
}
/// 获取本周的流量日志
Future<void> kr_getUserSubscribeTrafficLogs() async {
if (!KRAppRunData.getInstance().kr_isLogin.value) {
return;
}
final either0 = await KRUserApi().kr_getUserInfo();
either0.fold(
(error) => KRCommonUtil.kr_showToast(error.msg),
(userInfo) {
// kr_homeController.kr_userId.value = userInfo.id.toString();
},
);
// 获取本周的开始和结束时间戳
final DateTime now = DateTime.now();
final DateTime weekStart = now.subtract(Duration(days: now.weekday - 1));
final DateTime weekStartDate = DateTime(weekStart.year, weekStart.month, weekStart.day);
final DateTime weekEndDate = weekStartDate.add(const Duration(days: 7));
final int startTimestamp = weekStartDate.millisecondsSinceEpoch ~/ 1000;
final int endTimestamp = weekEndDate.millisecondsSinceEpoch ~/ 1000;
// 更新时间戳
kr_startTime.value = startTimestamp;
kr_endTime.value = endTimestamp;
final either = await KRUserApi().kr_getUserOnlineTimeStatistics();
either.fold(
(error) => KRCommonUtil.kr_showToast(error.msg),
(trafficLogs) {
// 处理流量日志数据
_kr_processTrafficLogs(trafficLogs);
},
);
}
/// 处理流量日志数据
void _kr_processTrafficLogs(KRUserOnlineDurationResponse trafficLogs) {
try {
// 更新连续记录数据
kr_currentStreak.value = trafficLogs.connectionRecords.currentContinuousDays;
kr_highestStreak.value = trafficLogs.connectionRecords.historyContinuousDays;
// 将小时转换为天数并向上取整
kr_longestConnection.value = (trafficLogs.connectionRecords.longestSingleConnection / 24).ceil();
// 更新每周数据
final List<double> weeklyHours = List.filled(7, 0.0);
for (final stat in trafficLogs.weeklyStats) {
if (stat.day >= 1 && stat.day <= 7) {
weeklyHours[stat.day - 1] = stat.hours;
}
}
kr_weeklyData.value = weeklyHours;
} catch (e) {
KRCommonUtil.kr_showToast('处理流量日志数据失败');
KRLogUtil.kr_e('处理流量日志数据失败: $e', tag: 'Statistics');
}
}
void _kr_updateVpnStatus(String value) {
kr_vpnStatus.value = value;
}
void _kr_updateIpAddress(String value) {
kr_ipAddress.value = value.isEmpty ? '0.0.0.0' : value;
}
void _kr_updateConnectionTime(String value) {
kr_connectTime.value = value.isEmpty ? '00:00:00' : value;
}
void _kr_updateProtocol(String value) {
kr_protocol.value = value.isEmpty ? 'UDP' : value;
}
/// 更新统计数据
void _kr_updateStatistics() {
// 不再需要本地更新统计数据,完全依赖接口返回
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
refreshController.dispose();
super.onClose();
}
/// 获取根据当前日期调整后的星期标题数组
List<String> kr_getAdjustedWeekTitles() {
final DateTime now = DateTime.now();
final int currentWeekday = now.weekday; // 1-71代表周一,7代表周日
final List<String> weekTitles = [
AppTranslations.kr_statistics.monday,
AppTranslations.kr_statistics.tuesday,
AppTranslations.kr_statistics.wednesday,
AppTranslations.kr_statistics.thursday,
AppTranslations.kr_statistics.friday,
AppTranslations.kr_statistics.saturday,
AppTranslations.kr_statistics.sunday
];
// 重新排序数组,使当前日期对应的星期显示在最后
final List<String> adjustedTitles = [
...weekTitles.sublist(currentWeekday),
...weekTitles.sublist(0, currentWeekday)
];
return adjustedTitles;
}
// 刷新数据
Future<void> kr_onRefresh() async {
if (!KRAppRunData.getInstance().kr_isLogin.value) {
refreshController.finishRefresh();
return;
}
try {
await kr_getUserSubscribeTrafficLogs();
} finally {
refreshController.finishRefresh();
}
}
}
+389
View File
@@ -0,0 +1,389 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import '../controllers/kr_statistics_controller.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:easy_refresh/easy_refresh.dart';
class KRStatisticsView extends GetView<KRStatisticsController> {
const KRStatisticsView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
backgroundColor: Theme.of(context).primaryColor ,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Align(
alignment: Alignment.centerLeft,
child: Text(
AppTranslations.kr_statistics.title,
style: KrAppTextStyle(
color: Theme.of(context).textTheme.bodyMedium?.color,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color.fromRGBO(23, 151, 255, 0.15), // 渐变开始颜色
Color.fromRGBO(23, 151, 255, 0.05), // 中间过渡颜色
// 非渐变色区域
],
stops: [0.0, 0.28], // 调整渐变结束位置
),
),
child: EasyRefresh(
controller: controller.refreshController,
onRefresh: controller.kr_onRefresh,
header: DeliveryHeader(
triggerOffset: 50.0,
springRebound: true,
),
child: SingleChildScrollView(
padding: EdgeInsets.zero,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// SizedBox(height: kToolbarHeight + 20.w),
_kr_buildStatusGrid(context),
_kr_buildWeeklyChart(context),
_kr_buildConnectionRecords(context),
],
),
),
),
),
);
}
// 构建状态网格
Widget _kr_buildStatusGrid(BuildContext context) {
// 根据平台调整卡片高度比例 - 优化桌面版本高度
final double aspectRatio = GetPlatform.isDesktop ? 165 / 38 : 165 / 82;
return Container(
padding: EdgeInsets.all(16.r),
child: GridView.count(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
crossAxisCount: 2,
mainAxisSpacing: 12.h,
crossAxisSpacing: 12.w,
childAspectRatio: aspectRatio, // 使用优化后的高度比例
children: [
Obx(() => _kr_buildStatusCard(
context,
AppTranslations.kr_statistics.vpnStatus,
controller.kr_vpnStatus.value,
Icons.link,
isError: true,
vpnStatusColor: controller.kr_vpnStatus.value == '已连接'
? const Color(0xFF67C23A)
: controller.kr_vpnStatus.value == '连接中...'
? const Color(0xFFE6A23C)
: const Color(0xFFF56C6C),
)),
Obx(() => _kr_buildStatusCard(
context,
AppTranslations.kr_statistics.ipAddress,
controller.kr_ipAddress.value,
Icons.language,
)),
Obx(() => _kr_buildStatusCard(
context,
AppTranslations.kr_statistics.connectionTime,
controller.kr_connectTime.value,
Icons.access_time,
)),
Obx(() => _kr_buildStatusCard(
context,
AppTranslations.kr_statistics.protocol,
controller.kr_protocol.value,
Icons.description_outlined,
)),
],
),
);
}
// 构建状态卡片
Widget _kr_buildStatusCard(BuildContext context, String title, String value, IconData icon, {bool isError = false, Color? vpnStatusColor}) {
return Container(
padding: EdgeInsets.all(16.r),
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12.r),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
icon,
color: vpnStatusColor ?? (isError ? Colors.red : Colors.blue),
size: 20.w,
),
SizedBox(width: 8.w),
Expanded(
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
title,
style: KrAppTextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: Theme.of(context).textTheme.bodyMedium?.color,
),
),
),
),
],
),
SizedBox(height: 8.w),
Text(
value,
style: KrAppTextStyle(
fontSize: 14,
color: vpnStatusColor ?? (isError ? Colors.red : Theme.of(context).textTheme.bodySmall?.color),
),
),
],
),
);
}
// 构建每周图表
Widget _kr_buildWeeklyChart(BuildContext context) {
return Container(
margin: EdgeInsets.all(16.r),
padding: EdgeInsets.fromLTRB(0, 16.r, 16.r, 16.r),
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12.r),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 16.r),
child: Text(
AppTranslations.kr_statistics.weeklyProtectionTime,
style: KrAppTextStyle(
fontSize: 14,
color: Theme.of(context).textTheme.bodyMedium?.color,
fontWeight: FontWeight.w500,
),
),
),
SizedBox(height: 16.w),
SizedBox(
height: 200.w,
child: Obx(() => LineChart(
LineChartData(
gridData: FlGridData(show: false),
titlesData: FlTitlesData(
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 40,
interval: 5,
getTitlesWidget: (value, meta) {
return Padding(
padding: EdgeInsets.only(left: 16.w),
child: Text(
value.toInt().toString(),
style: KrAppTextStyle(
color: Theme.of(context).textTheme.bodySmall?.color,
fontSize: 12,
),
),
);
},
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
interval: 1,
reservedSize: 30,
getTitlesWidget: (value, meta) {
final titles = controller.kr_getAdjustedWeekTitles();
int index = value.toInt();
if (index >= 0 && index < titles.length) {
return Text(
titles[index],
style: KrAppTextStyle(
color: Theme.of(context).textTheme.bodySmall?.color,
fontSize: 10,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
);
}
return const Text('');
},
),
),
rightTitles: AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
topTitles: AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
),
borderData: FlBorderData(show: false),
minX: 0,
maxX: 6,
minY: 0,
maxY: 20,
lineBarsData: [
LineChartBarData(
spots: controller.kr_weeklyData.asMap().entries.map((e) {
return FlSpot(e.key.toDouble(), e.value);
}).toList(),
isCurved: true,
color: Colors.blue,
barWidth: 2,
isStrokeCapRound: true,
dotData: FlDotData(show: false),
belowBarData: BarAreaData(
show: true,
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.blue.withOpacity(0.2),
Colors.blue.withOpacity(0.05),
],
),
),
),
],
),
)),
),
],
),
);
}
// 构建连接记录
Widget _kr_buildConnectionRecords(BuildContext context) {
return Container(
margin: EdgeInsets.all(16.r),
child: Column(
children: [
Row(
children: [
Expanded(
child: Obx(() => _kr_buildRecordCard(context, AppTranslations.kr_statistics.currentStreak, AppTranslations.kr_statistics.days(controller.kr_currentStreak.value))),
),
SizedBox(width: 16.w),
Expanded(
child: Obx(() => _kr_buildRecordCard(context, AppTranslations.kr_statistics.highestStreak, AppTranslations.kr_statistics.days(controller.kr_highestStreak.value))),
),
],
),
SizedBox(height: 16.w),
Obx(() => _kr_buildLongestConnection(context)),
],
),
);
}
// 构建记录卡片
Widget _kr_buildRecordCard(BuildContext context, String title, String value) {
return Container(
padding: EdgeInsets.all(16.r),
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12.r),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: KrAppTextStyle(
fontSize: 12,
color: Theme.of(context).textTheme.bodySmall?.color,
),
),
SizedBox(height: 8.w),
Text(
value,
style: KrAppTextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).textTheme.bodyMedium?.color,
),
),
],
),
);
}
// 构建最长连接时间
Widget _kr_buildLongestConnection(BuildContext context) {
return Container(
padding: EdgeInsets.all(16.r),
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12.r),
),
child: Row(
children: [
Container(
width: 40.w,
height: 40.w,
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.1),
shape: BoxShape.circle,
),
child: Icon(
Icons.access_time,
color: Colors.blue,
size: 24.w,
),
),
SizedBox(width: 16.w),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
AppTranslations.kr_statistics.longestConnection,
style: KrAppTextStyle(
fontSize: 12,
color: Theme.of(context).textTheme.bodySmall?.color,
),
),
Text(
AppTranslations.kr_statistics.days(controller.kr_longestConnection.value),
style: KrAppTextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Theme.of(context).textTheme.bodyMedium?.color,
),
),
],
),
),
],
),
);
}
}