Files
wushu/lib/views/active/popular_page.dart
2026-04-01 04:45:33 +08:00

536 lines
17 KiB
Dart

import 'package:flutter/material.dart';
import '../../constants/app_constants.dart';
import '../../utils/http/http_client.dart';
import '../../models/poetry_model.dart';
import '../../controllers/load/locally.dart';
import '../../controllers/history_controller.dart';
import '../../services/network_listener_service.dart';
/// 时间: 2026-03-25
/// 功能: 热门页面
/// 介绍: 展示诗词排行榜,包括总榜、日榜、月榜
/// 最新变化: 新建热门页面,支持多种排行榜类型
class PopularPage extends StatefulWidget {
const PopularPage({super.key});
@override
State<PopularPage> createState() => _PopularPageState();
}
class _PopularPageState extends State<PopularPage>
with SingleTickerProviderStateMixin {
late TabController _tabController;
final List<Map<String, dynamic>> _tabCategories = [
{'label': '总榜', 'icon': Icons.bar_chart},
{'label': '日榜', 'icon': Icons.today},
{'label': '月榜', 'icon': Icons.calendar_today},
];
List<PoetryModel> _rankList = [];
bool _loading = false;
String _errorMessage = '';
bool _showBottomIndicator = false;
@override
void initState() {
super.initState();
_tabController = TabController(length: _tabCategories.length, vsync: this);
_tabController.addListener(() {
if (mounted && !_tabController.indexIsChanging) {
_loadRankList();
}
});
_loadRankList();
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
// 黑色分割线
Container(height: 1, color: Colors.black.withValues(alpha: 0.1)),
// Tab栏
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: TabBar(
controller: _tabController,
tabs: _tabCategories
.map(
(category) => Tab(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(category['icon'], size: 16),
const SizedBox(width: 6),
Text(category['label']),
],
),
),
)
.toList(),
labelColor: AppConstants.primaryColor,
unselectedLabelColor: Colors.grey[600],
indicatorColor: AppConstants.primaryColor,
indicatorWeight: 3,
labelStyle: const TextStyle(fontWeight: FontWeight.bold),
),
),
// 内容区域
Expanded(
child: TabBarView(
controller: _tabController,
children: _tabCategories.map((category) {
return _buildRankContent(category['label']);
}).toList(),
),
),
],
);
}
Widget _buildRankContent(String category) {
if (_loading) {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('正在加载排行榜...'),
],
),
);
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(_errorMessage, style: const TextStyle(color: Colors.grey)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadRankList,
child: const Text('🔄 重试'),
),
],
),
);
}
if (_rankList.isEmpty) {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.bar_chart, size: 64, color: Colors.grey),
SizedBox(height: 16),
Text('暂无排行数据', style: TextStyle(color: Colors.grey)),
SizedBox(height: 8),
Text(
'换个时间段试试吧',
style: TextStyle(color: Colors.grey, fontSize: 12),
),
],
),
);
}
return RefreshIndicator(
onRefresh: () async => await _loadRankList(forceRefresh: true),
child: NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollEndNotification &&
scrollNotification.metrics.extentAfter == 0) {
_showBottomIndicatorMethod();
}
return false;
},
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: _rankList.length + (_showBottomIndicator ? 1 : 0),
itemBuilder: (context, index) {
if (index == _rankList.length) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('到底了', style: TextStyle(color: Colors.grey)),
),
);
}
return _buildRankItem(_rankList[index], index + 1);
},
),
),
);
}
Future<void> _createNoteFromPoetry(PoetryModel poetry) async {
try {
final title = poetry.name.isNotEmpty ? poetry.name : '诗词笔记';
final category = poetry.alias.isNotEmpty ? poetry.alias : '诗词';
final contentBuffer = StringBuffer();
if (poetry.url.isNotEmpty) {
contentBuffer.writeln('出处:${poetry.url}');
}
if (poetry.name.isNotEmpty) {
contentBuffer.writeln('诗句:${poetry.name}');
}
if (poetry.alias.isNotEmpty) {
contentBuffer.writeln('朝代:${poetry.alias}');
}
final noteId = await HistoryController.saveNote(
title: title,
content: contentBuffer.toString().trim(),
category: category,
);
if (noteId != null) {
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: noteId,
);
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已创建笔记')));
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('创建笔记失败: $e')));
}
}
}
Widget _buildRankItem(PoetryModel poetry, int index) {
final rank = poetry.rank > 0 ? poetry.rank : index;
final isTopThree = rank <= 3;
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: isTopThree ? 4 : 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(
color: isTopThree
? AppConstants.primaryColor
: AppConstants.primaryColor.withValues(alpha: 0.2),
width: isTopThree ? 2 : 1,
),
),
child: InkWell(
onTap: () => _onViewDetail(poetry),
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Stack(
clipBehavior: Clip.none,
children: [
Row(
children: [
// 排名徽章
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: isTopThree
? AppConstants.primaryColor
: AppConstants.primaryColor.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(20),
border: isTopThree
? null
: Border.all(
color: AppConstants.primaryColor.withValues(
alpha: 0.2,
),
width: 1,
),
),
child: Center(
child: Text(
rank.toString(),
style: TextStyle(
color: isTopThree
? Colors.white
: AppConstants.primaryColor.withValues(
alpha: 0.8,
),
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
),
const SizedBox(width: 12),
// 内容区域
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 标题
Text(
poetry.name,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// 朝代和作者
if (poetry.alias.isNotEmpty || poetry.url.isNotEmpty)
Row(
children: [
if (poetry.alias.isNotEmpty) ...[
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: AppConstants.primaryColor.withValues(
alpha: 0.1,
),
borderRadius: BorderRadius.circular(8),
),
child: Text(
poetry.alias,
style: TextStyle(
fontSize: 10,
color: AppConstants.primaryColor,
),
),
),
const SizedBox(width: 8),
],
if (poetry.url.isNotEmpty)
Expanded(
child: Text(
poetry.url,
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 8),
// 统计数据
Row(
children: [
_buildStatItem(
'👁',
poetry.hitsTotal.toString(),
'总浏览',
),
const SizedBox(width: 16),
_buildStatItem('💖', poetry.like.toString(), '点赞'),
const SizedBox(width: 16),
if (_tabController.index == 1)
_buildStatItem(
'📅',
poetry.hitsDay.toString(),
'今日',
),
if (_tabController.index == 2)
_buildStatItem(
'📊',
poetry.hitsMonth.toString(),
'本月',
),
],
),
],
),
),
],
),
// 添加笔记按钮 - 位于右下角,可遮挡字段
Positioned(
bottom: -8,
right: -8,
child: GestureDetector(
onTap: () => _createNoteFromPoetry(poetry),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 6,
),
decoration: BoxDecoration(
color: Colors.orange[700],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.15),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.note_add,
size: 14,
color: Colors.white,
),
const SizedBox(width: 4),
const Text(
'笔记',
style: TextStyle(
fontSize: 11,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
),
],
),
),
),
);
}
Widget _buildStatItem(String icon, String value, String label) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(icon, style: const TextStyle(fontSize: 12)),
const SizedBox(width: 4),
Text(
value,
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
),
const SizedBox(width: 2),
Text(label, style: TextStyle(fontSize: 10, color: Colors.grey[600])),
],
);
}
Future<void> _loadRankList({bool forceRefresh = false}) async {
setState(() {
_loading = true;
_errorMessage = '';
_showBottomIndicator = false;
});
try {
final tabIndex = _tabController.index;
final type = tabIndex == 0
? 'total'
: tabIndex == 1
? 'day'
: 'month';
final isPreloadEnabled = await LocalCacheManager().isPreloadEnabled();
if (isPreloadEnabled && !forceRefresh) {
final cachedData = await LocalCacheManager().getCachedPopularList(type);
if (cachedData != null && cachedData.isNotEmpty) {
if (mounted) {
setState(() {
_rankList = cachedData
.map((item) => PoetryModel.fromJson(item))
.toList();
_loading = false;
});
}
return;
}
}
final response = await HttpClient.get(
'/rlist.php',
queryParameters: {'type': type, 'limit': '20'},
);
if (response.isSuccess && response.code == 0) {
final data = response.data;
final rankData = data['list'] as List<dynamic>? ?? [];
final rankDataList = rankData.cast<Map<String, dynamic>>();
if (isPreloadEnabled) {
await LocalCacheManager().cachePopularList(type, rankDataList);
}
if (mounted) {
setState(() {
_rankList = rankData
.map((item) => PoetryModel.fromJson(item))
.toList();
_loading = false;
});
}
} else {
if (mounted) {
setState(() {
_errorMessage = response.message.isNotEmpty == true
? response.message
: '获取排行榜失败';
_loading = false;
});
}
}
} catch (e) {
if (mounted) {
setState(() {
_errorMessage = '网络请求失败,请检查网络连接';
_loading = false;
});
}
}
}
void _showBottomIndicatorMethod() {
if (_rankList.isNotEmpty && !_loading && mounted) {
setState(() {
_showBottomIndicator = true;
});
Future.delayed(const Duration(seconds: 3), () {
if (mounted) {
setState(() {
_showBottomIndicator = false;
});
}
});
}
}
void _onViewDetail(PoetryModel poetry) {
// TODO: 跳转到诗词详情页面
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('查看诗词: ${poetry.name}'),
duration: const Duration(seconds: 1),
),
);
}
}