结构重构

This commit is contained in:
DelLevin-Home
2026-06-25 23:56:12 +08:00
parent 00e948e580
commit ec46d45973
8 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,755 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import '../utils/server_config.dart';
import '../utils/user_prefs.dart';
import '../models/data_models.dart';
import '../providers/app_provider.dart';
import '../utils/image_path_helper.dart';
import '../utils/toast_util.dart';
/// 书籍详情页 - 在线版
class BookDetailPage extends StatefulWidget {
final String bookId;
const BookDetailPage({super.key, required this.bookId});
@override
State<BookDetailPage> createState() => _BookDetailPageState();
}
class _BookDetailPageState extends State<BookDetailPage> {
Map<String, dynamic>? _data;
bool _loading = true;
String? _error;
Book? _localBook;
String? _catalog;
bool _catalogLoading = false;
int _currentTab = 0;
@override
void initState() {
super.initState();
_load();
}
String _resolveCoverUrl(String cover) {
if (cover.startsWith('http')) return cover;
return '${ServerConfig.vipBaseUrl}/mk_book$cover';
}
Future<void> _load() async {
final token = UserPrefs().bookSearchToken;
try {
final url = '${ServerConfig.vipBaseUrl}/api/book/detail?id=${widget.bookId}&token=$token';
final resp = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 10));
if (!mounted) return;
if (resp.statusCode == 200) {
final json_ = json.decode(resp.body);
if (json_['code'] == 0 && json_['data'] != null) {
setState(() {
_data = json_['data'];
_loading = false;
});
_checkLocal();
_loadCatalog();
return;
}
}
setState(() {
_error = '加载失败';
_loading = false;
});
} catch (_) {
if (mounted) setState(() {
_error = '网络错误';
_loading = false;
});
}
}
void _checkLocal() {
final title = _data?['title'] ?? '';
if (title.toString().isEmpty) return;
final provider = context.read<AppProvider>();
final match = provider.books.where((b) => !b.isDeleted && b.title == title).toList();
if (match.isNotEmpty) {
setState(() => _localBook = match.first);
}
}
String _decodeText(List<int> bytes) {
if (bytes.length >= 2) {
// UTF-16 LE BOM: FF FE
if (bytes[0] == 0xFF && bytes[1] == 0xFE) {
final codes = <int>[];
for (var i = 2; i + 1 < bytes.length; i += 2) {
codes.add(bytes[i] | (bytes[i + 1] << 8));
}
return String.fromCharCodes(codes);
}
// UTF-16 BE BOM: FE FF
if (bytes[0] == 0xFE && bytes[1] == 0xFF) {
final codes = <int>[];
for (var i = 2; i + 1 < bytes.length; i += 2) {
codes.add((bytes[i] << 8) | bytes[i + 1]);
}
return String.fromCharCodes(codes);
}
}
// 无 BOM按 UTF-16 LE 尝试(大部分中文 txt 是这种)
if (bytes.length >= 2 && bytes.length % 2 == 0) {
final codes = <int>[];
for (var i = 0; i + 1 < bytes.length; i += 2) {
codes.add(bytes[i] | (bytes[i + 1] << 8));
}
final text = String.fromCharCodes(codes);
// 检查解码结果是否包含大量不可打印字符(说明不是 UTF-16
final printable = text.runes.where((r) => r >= 0x20 && r < 0xFFFF).length;
if (printable > text.length * 0.8) return text;
}
// fallback: UTF-8
try {
return utf8.decode(bytes);
} catch (_) {
return String.fromCharCodes(bytes);
}
}
Future<void> _loadCatalog() async {
final bookmark = _data?['bookmark'] ?? '';
if (bookmark.toString().isEmpty) return;
setState(() => _catalogLoading = true);
try {
final bookmarkStr = bookmark.toString();
final bookmarkUrl = bookmarkStr.startsWith('http')
? bookmarkStr
: '${ServerConfig.vipBaseUrl}/mk_book/$bookmarkStr';
final resp = await http.get(
Uri.parse(bookmarkUrl),
headers: {'Accept-Encoding': 'identity'},
).timeout(const Duration(seconds: 10));
if (!mounted) return;
if (resp.statusCode == 200) {
final bytes = resp.bodyBytes;
final text = _decodeText(bytes);
setState(() {
_catalog = text;
_catalogLoading = false;
});
return;
}
} catch (_) {}
if (mounted) setState(() => _catalogLoading = false);
}
Future<void> _addBook(String status) async {
final m = _data!;
final title = m['title'] ?? '';
final author = m['author'] ?? '';
final press = m['press'] ?? '';
final isbn = m['isbn'] ?? '';
final yearStr = m['publishedDate'] ?? '';
final cover = m['cover'] ?? '';
DateTime? publishDate;
if (yearStr.toString().isNotEmpty) {
publishDate = DateTime.tryParse('${yearStr}-01-01');
}
final bookId = const Uuid().v4();
String? coverPath;
if (cover.toString().isNotEmpty) {
try {
final coverUrl = _resolveCoverUrl(cover.toString());
final resp = await http.get(Uri.parse(coverUrl), headers: {
'User-Agent': 'Mozilla/5.0'
}).timeout(const Duration(seconds: 15));
if (resp.statusCode == 200 && resp.bodyBytes.length < 10 * 1024 * 1024) {
final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg';
final targetPath = await ImagePathHelper.instance.getBookCoverPath(bookId, fileName);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
await File(targetPath).writeAsBytes(resp.bodyBytes);
coverPath = targetPath;
}
} catch (_) {}
}
final book = Book(
id: bookId,
title: title.toString(),
coverPath: coverPath,
authors: _splitStr(author.toString()),
publisher: press.toString(),
isbn: isbn.toString(),
publishDate: publishDate,
status: status,
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
);
if (!mounted) return;
final provider = context.read<AppProvider>();
await provider.addBook(book);
if (mounted) {
setState(() {
_localBook = provider.books.firstWhere((b) => b.id == book.id);
});
ToastUtil.show(context, '已添加到${_statusLabel(status)}');
}
}
List<String> _splitStr(String s) => s
.split(RegExp(r'[,/、]'))
.map((e) => e.trim())
.where((e) => e.isNotEmpty)
.toList();
String _statusLabel(String status) {
switch (status) {
case 'read':
return '已读';
case 'reading':
return '在读';
case 'want_to_read':
return '想读';
default:
return '';
}
}
void _showAddSheet() {
final colors = Theme.of(context).colorScheme;
showModalBottomSheet(
context: context,
backgroundColor: colors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
builder: (ctx) => SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 16),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Center(
child: Container(
width: 36,
height: 4,
margin: const EdgeInsets.only(bottom: 14),
decoration: BoxDecoration(
color: colors.onSurface.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(2)))),
Text('添加到',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: colors.onSurface)),
const SizedBox(height: 14),
_sheetItem(ctx, colors, Icons.check_circle_outline, '已读', 'read'),
_sheetItem(ctx, colors, Icons.play_circle_outline, '在读', 'reading'),
_sheetItem(ctx, colors, Icons.bookmark_outline, '想读', 'want_to_read'),
]),
),
),
);
}
Widget _sheetItem(BuildContext ctx, ColorScheme colors, IconData icon,
String label, String status) {
return InkWell(
onTap: () {
Navigator.pop(ctx);
_addBook(status);
},
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
margin: const EdgeInsets.only(bottom: 4),
child: Row(children: [
Icon(icon, size: 22, color: colors.onSurface.withValues(alpha: 0.6)),
const SizedBox(width: 12),
Text(label,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: colors.onSurface)),
]),
),
);
}
// ── Build ──────────────────────────────────────────────
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: colors.surface,
floatingActionButton:
(!_loading && _error == null && _localBook == null && _data != null)
? FloatingActionButton(
onPressed: _showAddSheet,
backgroundColor: colors.primary,
child: Icon(Icons.add, color: colors.onPrimary))
: null,
body: _loading
? Center(child: CircularProgressIndicator(color: colors.primary, strokeWidth: 2))
: _error != null
? _buildError(colors)
: _buildBody(colors),
);
}
Widget _buildError(ColorScheme colors) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 48, color: colors.onSurface.withValues(alpha: 0.2)),
const SizedBox(height: 16),
Text(_error!, style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.4))),
const SizedBox(height: 16),
TextButton(
onPressed: () {
setState(() { _loading = true; _error = null; });
_load();
},
child: Text('重试', style: TextStyle(color: colors.primary))),
],
));
}
Widget _buildBody(ColorScheme colors) {
final m = _data!;
final cover = m['cover'] ?? '';
final title = m['title'] ?? '';
final author = m['author'] ?? '';
final press = m['press'] ?? '';
final isbn = m['isbn'] ?? '';
final year = m['publishedDate'] ?? '';
final pages = m['pagination'];
final coverUrl = cover.toString().isNotEmpty ? _resolveCoverUrl(cover.toString()) : '';
return Column(children: [
// 顶部固定区域
Container(
color: colors.surface,
child: SafeArea(
bottom: false,
child: Column(children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(children: [
GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
shape: BoxShape.circle),
child: Icon(Icons.arrow_back, size: 20, color: colors.onSurface)),
),
]),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 110,
height: 160,
child: coverUrl.isNotEmpty
? Image.network(coverUrl,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _coverPlaceholder(colors))
: _coverPlaceholder(colors),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: colors.onSurface)),
if (author.toString().isNotEmpty) ...[
const SizedBox(height: 8),
Text(author, style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
],
if (press.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text(press, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.45))),
],
if (year.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text('出版年份:$year', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (isbn.toString().isNotEmpty) ...[
const SizedBox(height: 4),
Text('ISBN$isbn', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (pages != null && pages != 0) ...[
const SizedBox(height: 4),
Text('页数:$pages', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (_localBook != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
),
]),
),
]),
),
),
// Tab 栏
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Row(children: [
_buildTabButton('基础信息', 0),
_buildTabButton('国图信息', 1),
_buildTabButton('网购地址', 2),
_buildTabButton('书籍目录', 3),
]),
),
// 内容区
Expanded(
child: _currentTab == 0
? _buildBasicInfo(colors)
: _currentTab == 1
? _buildOpacTab(colors)
: _currentTab == 2
? _buildOnlineTab(colors)
: _buildCatalogTab(colors),
),
]);
}
Widget _buildTabButton(String label, int index) {
final colors = Theme.of(context).colorScheme;
final selected = _currentTab == index;
return GestureDetector(
onTap: () => setState(() => _currentTab = index),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 11),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: selected ? colors.primary : Colors.transparent,
width: 2))),
child: Text(label,
style: TextStyle(
fontSize: 13,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
color: selected
? colors.primary
: colors.onSurface.withValues(alpha: 0.4))),
),
);
}
// ── 基础信息 Tab ──────────────────────────────────────────
Widget _buildBasicInfo(ColorScheme colors) {
final m = _data!;
final tags = m['tags'] ?? '';
final sub1 = m['sub1'] ?? '';
final sub2 = m['sub2'] ?? '';
return ListView(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 40),
children: [
// 分类
_buildSectionTitle(colors, '分类', Icons.category_outlined),
const SizedBox(height: 6),
if (sub1.toString().isNotEmpty)
_buildChipWrap(colors, sub1.toString().split(RegExp(r'[,]')))
else
_buildEmptyHint(colors),
const SizedBox(height: 16),
// 标签
_buildSectionTitle(colors, '标签', Icons.sell_outlined),
const SizedBox(height: 6),
if (tags.toString().isNotEmpty)
_buildChipWrap(colors, tags.toString().split(RegExp(r'[,]')))
else
_buildEmptyHint(colors),
const SizedBox(height: 16),
// 内容简介
_buildSectionTitle(colors, '内容简介', Icons.article_outlined),
const SizedBox(height: 8),
if (sub2.toString().isNotEmpty)
Text(sub2.toString().replaceAll(RegExp(r'<[^>]*>'), ''),
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.7), height: 1.7))
else
_buildEmptyHint(colors),
],
);
}
Widget _buildEmptyHint(ColorScheme colors) {
return Text('暂无该信息数据',
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.3)));
}
// ── 国图信息 Tab ──────────────────────────────────────────
Widget _buildOpacTab(ColorScheme colors) {
final opacStr = _data?['opacInfo'];
Map<String, dynamic>? opac;
if (opacStr != null && opacStr.toString().isNotEmpty) {
try { opac = json.decode(opacStr.toString()); } catch (_) {}
}
if (opac == null) {
return Center(
child: Text('暂无国图信息',
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.35))));
}
return ListView(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 40),
children: [
_buildOpacInfo(colors, opac),
],
);
}
// ── 网购地址 Tab ──────────────────────────────────────────
Widget _buildOnlineTab(ColorScheme colors) {
final onlineStr = _data?['online'];
List<Map<String, dynamic>> links = [];
if (onlineStr != null && onlineStr.toString().isNotEmpty) {
try {
final list = json.decode(onlineStr.toString()) as List;
links = list.map((e) => e as Map<String, dynamic>).toList();
} catch (_) {}
}
if (links.isEmpty) {
return Center(
child: Text('暂无网购地址',
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.35))));
}
return ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 40),
itemCount: links.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) => _buildOnlineLink(colors, links[index]),
);
}
// ── 书籍目录 Tab ──────────────────────────────────────────
Widget _buildCatalogTab(ColorScheme colors) {
if (_catalogLoading) {
return Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: colors.primary)));
}
if (_catalog == null || _catalog!.isEmpty) {
return Center(
child: Text('暂无目录信息',
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.35))));
}
final lines = _catalog!.split('\n').where((l) => l.trim().isNotEmpty).toList();
return ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 40),
itemCount: lines.length,
itemBuilder: (context, index) {
final text = lines[index].trim();
final level = _detectLevel(text);
final indent = level * 16.0;
final isMain = level == 0;
return Padding(
padding: EdgeInsets.only(left: 8 + indent, top: isMain ? 10 : 4, bottom: isMain ? 2 : 1),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isMain)
Container(
width: 3, height: 14,
margin: const EdgeInsets.only(right: 8, top: 2),
decoration: BoxDecoration(
color: colors.primary.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(1.5),
),
),
Expanded(
child: Text(text, style: TextStyle(
fontSize: isMain ? 13.5 : 12.5,
fontWeight: isMain ? FontWeight.w600 : FontWeight.w400,
color: isMain ? colors.onSurface.withValues(alpha: 0.85) : colors.onSurface.withValues(alpha: 0.55),
height: 1.4,
)),
),
],
),
);
},
);
}
// ── 通用组件 ──────────────────────────────────────────────
Widget _buildSectionTitle(ColorScheme colors, String title, IconData icon) {
return Row(
children: [
Icon(icon, size: 15, color: colors.primary.withValues(alpha: 0.7)),
const SizedBox(width: 6),
Text(title, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: colors.onSurface)),
],
);
}
Widget _buildChipWrap(ColorScheme colors, List<String> items) {
return Wrap(
spacing: 6,
runSpacing: 6,
children: items.where((t) => t.trim().isNotEmpty).map((t) => Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: colors.outlineVariant, width: 0.5),
),
child: Text(t.trim(), style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.65))),
)).toList(),
);
}
Widget _buildOpacInfo(ColorScheme colors, Map<String, dynamic> opac) {
final items = <List<String>>[];
if (opac['title'] != null && opac['title'].toString().isNotEmpty) items.add(['题名', opac['title'].toString()]);
if (opac['authors'] != null) {
final authors = (opac['authors'] as List).map((e) => e.toString()).join('');
if (authors.isNotEmpty) items.add(['作者', authors]);
}
if (opac['publisher'] != null && opac['publisher'].toString().isNotEmpty) items.add(['出版社', opac['publisher'].toString()]);
if (opac['pubdate'] != null && opac['pubdate'].toString().isNotEmpty) items.add(['出版日期', opac['pubdate'].toString()]);
if (opac['isbn'] != null && opac['isbn'].toString().isNotEmpty) items.add(['ISBN', opac['isbn'].toString()]);
if (opac['clc'] != null && opac['clc'].toString().isNotEmpty) items.add(['中图分类号', opac['clc'].toString()]);
if (opac['tags'] != null && opac['tags'].toString().isNotEmpty) items.add(['主题词', opac['tags'].toString()]);
if (items.isEmpty) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: items.map((pair) => Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 72,
child: Text(pair[0], style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
),
Expanded(
child: Text(pair[1], style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.75), height: 1.4)),
),
],
),
)).toList(),
),
);
}
Widget _buildOnlineLink(ColorScheme colors, Map<String, dynamic> link) {
final source = link['source'] ?? '';
final url = link['url'] ?? '';
if (source.toString().isEmpty || url.toString().isEmpty) return const SizedBox.shrink();
return GestureDetector(
onTap: () => launchUrl(Uri.parse(url.toString()), mode: LaunchMode.externalApplication),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Icon(Icons.link, size: 16, color: colors.primary.withValues(alpha: 0.6)),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(source.toString(), style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface)),
const SizedBox(height: 2),
Text(url.toString(), style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.35)), maxLines: 1, overflow: TextOverflow.ellipsis),
],
),
),
Icon(Icons.chevron_right, size: 16, color: colors.onSurface.withValues(alpha: 0.3)),
],
),
),
);
}
/// 检测目录层级0=主章节, 1=子章节
int _detectLevel(String line) {
// 主章节第X章、第X篇、Chapter X、数字+点开头(如 "1. "
if (RegExp(r'^第[一二三四五六七八九十百千\d]+[章篇部回卷]').hasMatch(line)) return 0;
if (RegExp(r'^Chapter\s+\d+', caseSensitive: false).hasMatch(line)) return 0;
if (RegExp(r'^\d+[\.\s、]').hasMatch(line)) return 0;
if (RegExp(r'^[一二三四五六七八九十]+[、..]').hasMatch(line)) return 0;
// 子章节第X节、数字.数字(如 "1.1 "
if (RegExp(r'^第[一二三四五六七八九十百千\d]+[节]').hasMatch(line)) return 1;
if (RegExp(r'^\d+\.\d+[\.\s、]').hasMatch(line)) return 1;
if (RegExp(r'^[(]\d+[)]').hasMatch(line)) return 1;
if (line.startsWith(' ') || line.startsWith('\t')) return 1;
// 默认主章节
return 0;
}
Widget _coverPlaceholder(ColorScheme colors) {
return Container(
color: colors.surfaceContainerHighest,
child: Center(
child: Icon(Icons.menu_book_outlined,
size: 32, color: colors.onSurface.withValues(alpha: 0.15))));
}
Widget _buildLocalStatus(ColorScheme colors) {
final status = _localBook!.status;
final label = _statusLabel(status);
Color dotColor;
switch (status) {
case 'read':
dotColor = colors.primary;
break;
case 'reading':
dotColor = const Color(0xFF666666);
break;
default:
dotColor = const Color(0xFF999999);
break;
}
return Row(children: [
Container(
width: 6,
height: 6,
decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle)),
const SizedBox(width: 6),
Text('已在本地 · $label',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: colors.onSurface.withValues(alpha: 0.6))),
]);
}
}

View File

@@ -0,0 +1,473 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../utils/user_prefs.dart';
import '../utils/server_config.dart';
import 'legal_page.dart';
/// 增强搜索设置页面
class EnhancedSearchSettingsPage extends StatefulWidget {
const EnhancedSearchSettingsPage({super.key});
@override
State<EnhancedSearchSettingsPage> createState() =>
_EnhancedSearchSettingsPageState();
}
class _EnhancedSearchSettingsPageState
extends State<EnhancedSearchSettingsPage> {
final _userPrefs = UserPrefs();
final _movieTokenController = TextEditingController();
final _bookTokenController = TextEditingController();
bool _enabled = false;
// null=未验证/检查中, true=有效, false=无效
bool? _movieTokenValid;
bool? _bookTokenValid;
String? _movieTokenMessage;
String? _bookTokenMessage;
@override
void initState() {
super.initState();
_enabled = _userPrefs.enhancedSearchEnabled;
_movieTokenController.text = _userPrefs.movieSearchToken;
_bookTokenController.text = _userPrefs.bookSearchToken;
if (_enabled) _verifyTokens();
}
@override
void dispose() {
_movieTokenController.dispose();
_bookTokenController.dispose();
super.dispose();
}
Future<void> _verifyTokens() async {
final movieToken = _movieTokenController.text.trim();
final bookToken = _bookTokenController.text.trim();
if (movieToken.isNotEmpty) {
_checkToken(movieToken, 'movie').then((result) async {
if (!mounted) return;
final valid = result != null && result['valid'] == true;
if (valid) {
setState(() {
_movieTokenValid = true;
_movieTokenMessage = result['messageString'] as String?;
});
} else {
// 当前类型失败,用另一种类型重试
final retry = await _checkToken(movieToken, 'book');
if (!mounted) return;
setState(() {
_movieTokenValid = false;
_movieTokenMessage = retry != null && retry['valid'] == true
? '该 Token 可能是书籍类型,请检查是否填错位置'
: ((result != null ? result['messageString'] as String? : null) ?? '验证失败');
});
}
});
}
if (bookToken.isNotEmpty) {
_checkToken(bookToken, 'book').then((result) async {
if (!mounted) return;
final valid = result != null && result['valid'] == true;
if (valid) {
setState(() {
_bookTokenValid = true;
_bookTokenMessage = result['messageString'] as String?;
});
} else {
final retry = await _checkToken(bookToken, 'movie');
if (!mounted) return;
setState(() {
_bookTokenValid = false;
_bookTokenMessage = retry != null && retry['valid'] == true
? '该 Token 可能是影视类型,请检查是否填错位置'
: ((result != null ? result['messageString'] as String? : null) ?? '验证失败');
});
}
});
}
}
Future<Map<String, dynamic>?> _checkToken(String token, String type) async {
try {
final url = '${ServerConfig.vipBaseUrl}/api/token/check?token=$token&type=$type';
final resp =
await http.get(Uri.parse(url)).timeout(const Duration(seconds: 8));
if (resp.statusCode == 200) {
final data = json.decode(resp.body);
if (data['code'] == 0 && data['data'] != null) {
return data['data'] as Map<String, dynamic>;
}
}
} catch (_) {}
return null;
}
Future<void> _toggle(bool value) async {
if (value) {
await _userPrefs.setMovieSearchToken(_movieTokenController.text.trim());
await _userPrefs.setBookSearchToken(_bookTokenController.text.trim());
await _userPrefs.setEnhancedSearchEnabled(true);
setState(() => _enabled = true);
_verifyTokens();
} else {
await _userPrefs.setEnhancedSearchEnabled(false);
setState(() {
_enabled = false;
_movieTokenValid = null;
_bookTokenValid = null;
_movieTokenMessage = null;
_bookTokenMessage = null;
});
}
}
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: colors.surface,
appBar: AppBar(
title: const Text('增强搜索'),
actions: [
if (_enabled)
IconButton(
icon: const Icon(Icons.refresh),
tooltip: '刷新验证',
onPressed: () {
setState(() {
_movieTokenValid = null;
_bookTokenValid = null;
_movieTokenMessage = null;
_bookTokenMessage = null;
});
_verifyTokens();
},
),
],
),
body: ListView(
padding: const EdgeInsets.all(20),
children: [
_buildSwitchRow(colors),
const SizedBox(height: 16),
_buildStatusBanner(colors),
const SizedBox(height: 20),
_buildSectionLabel(colors, '影视增强搜索 Token'),
const SizedBox(height: 8),
_buildTokenInput(
colors: colors,
controller: _movieTokenController,
hint: '输入影视搜索 Token',
valid: _movieTokenValid,
message: _movieTokenMessage,
),
const SizedBox(height: 16),
_buildSectionLabel(colors, '书籍增强搜索 Token'),
const SizedBox(height: 8),
_buildTokenInput(
colors: colors,
controller: _bookTokenController,
hint: '输入书籍搜索 Token',
valid: _bookTokenValid,
message: _bookTokenMessage,
),
const SizedBox(height: 28),
_buildSaveButton(colors),
const SizedBox(height: 32),
_buildTips(colors),
],
),
);
}
Widget _buildSwitchRow(ColorScheme colors) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: colors.outlineVariant, width: 0.5),
),
child: Row(
children: [
Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: _enabled
? colors.primary.withValues(alpha: 0.1)
: colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Icon(Icons.manage_search,
size: 18,
color: _enabled
? colors.primary
: colors.onSurface.withValues(alpha: 0.5)),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('增强搜索',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500,
color: colors.onSurface)),
const SizedBox(height: 1),
Text(_enabled ? '已开启' : '未开启',
style: TextStyle(
fontSize: 11,
color: colors.onSurface.withValues(alpha: 0.4))),
],
),
),
Switch(
value: _enabled,
onChanged: _toggle,
activeThumbColor: colors.primary,
activeTrackColor: colors.primary.withValues(alpha: 0.3),
inactiveThumbColor: colors.surface,
inactiveTrackColor: colors.outline,
),
],
),
);
}
Widget _buildStatusBanner(ColorScheme colors) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: _enabled
? const Color(0xFF16A34A).withValues(alpha: 0.08)
: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: _enabled
? const Color(0xFF16A34A).withValues(alpha: 0.3)
: colors.outlineVariant,
width: 0.5,
),
),
child: Row(
children: [
Icon(
_enabled ? Icons.check_circle_outline : Icons.info_outline,
size: 18,
color: _enabled
? const Color(0xFF16A34A)
: colors.onSurface.withValues(alpha: 0.4),
),
const SizedBox(width: 10),
Expanded(
child: Text(
_enabled ? '增强搜索已开启' : '填写 Token 后开启增强搜索',
style: TextStyle(
fontSize: 13,
color: _enabled
? const Color(0xFF16A34A)
: colors.onSurface.withValues(alpha: 0.6),
),
),
),
],
),
);
}
Widget _buildSectionLabel(ColorScheme colors, String text) {
return Text(text,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: colors.onSurface.withValues(alpha: 0.5)));
}
Widget _buildTokenInput({
required ColorScheme colors,
required TextEditingController controller,
required String hint,
bool? valid,
String? message,
}) {
return Column(
children: [
Container(
height: 40,
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: colors.outlineVariant, width: 0.5),
),
child: Row(
children: [
const SizedBox(width: 12),
Icon(Icons.key,
size: 16, color: colors.onSurface.withValues(alpha: 0.3)),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: controller,
style: TextStyle(fontSize: 13, color: colors.onSurface),
decoration: InputDecoration(
hintText: hint,
hintStyle: TextStyle(
fontSize: 13,
color: colors.onSurface.withValues(alpha: 0.3)),
isDense: true,
contentPadding: EdgeInsets.zero,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
filled: false,
),
),
),
const SizedBox(width: 12),
],
),
),
if (_enabled && valid != null)
Padding(
padding: const EdgeInsets.only(top: 6, left: 4),
child: Row(
children: [
Icon(
valid ? Icons.check_circle : Icons.cancel,
size: 14,
color: valid ? const Color(0xFF16A34A) : colors.error,
),
const SizedBox(width: 6),
Expanded(
child: Text(
message ?? (valid ? 'Token 有效' : 'Token 无效'),
style: TextStyle(
fontSize: 11,
color: valid ? const Color(0xFF16A34A) : colors.error),
),
),
],
),
),
if (_enabled && valid == null && controller.text.trim().isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6, left: 4),
child: Row(
children: [
SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 1.5,
color: colors.onSurface.withValues(alpha: 0.3))),
const SizedBox(width: 6),
Text('验证中...',
style: TextStyle(
fontSize: 11,
color: colors.onSurface.withValues(alpha: 0.4))),
],
),
),
],
);
}
Future<void> _saveAndVerify() async {
await _userPrefs.setMovieSearchToken(_movieTokenController.text.trim());
await _userPrefs.setBookSearchToken(_bookTokenController.text.trim());
setState(() {
_movieTokenValid = null;
_bookTokenValid = null;
_movieTokenMessage = null;
_bookTokenMessage = null;
});
_verifyTokens();
}
Widget _buildSaveButton(ColorScheme colors) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
GestureDetector(
onTap: _saveAndVerify,
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: colors.primary,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text('保存并验证', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: colors.onPrimary)),
),
),
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(
builder: (_) => const LegalPage(slug: 'token_doc', title: '获取Token'))),
child: Text('点击获取 Token', style: TextStyle(fontSize: 12, color: colors.primary)),
),
),
],
);
}
Widget _buildTips(ColorScheme colors) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('说明',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: colors.onSurface.withValues(alpha: 0.4),
letterSpacing: 0.5)),
const SizedBox(height: 10),
_tip(colors, '增强搜索可在线检索影视和书籍的详细信息'),
_tip(colors, 'Token 过期或失效后需重新获取并填写'),
_tip(colors, '作者会在 QQ 群不定期发放增强搜索的token'),
],
),
);
}
Widget _tip(ColorScheme colors, String text) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 7),
child: Icon(Icons.circle,
size: 4, color: colors.onSurface.withValues(alpha: 0.25)),
),
const SizedBox(width: 8),
Expanded(
child: Text(text,
style: TextStyle(
fontSize: 12,
color: colors.onSurface.withValues(alpha: 0.5),
height: 1.5))),
],
),
);
}
}

View File

@@ -0,0 +1,910 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import '../utils/server_config.dart';
import '../utils/user_prefs.dart';
import '../models/data_models.dart';
import '../providers/app_provider.dart';
import '../utils/image_path_helper.dart';
import '../utils/toast_util.dart';
/// 影视详情页 - 在线版
class MovieDetailPage extends StatefulWidget {
final int vodId;
const MovieDetailPage({super.key, required this.vodId});
@override
State<MovieDetailPage> createState() => _MovieDetailPageState();
}
class _MovieDetailPageState extends State<MovieDetailPage> {
Map<String, dynamic>? _data;
List<Map<String, dynamic>> _staffList = [];
bool _loading = true;
bool _staffLoading = false;
String? _error;
bool _expanded = false;
Movie? _localMovie;
int _currentTab = 0;
int _detailStyle = 0; // 0: 紧凑, 1: 沉浸式
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final token = UserPrefs().movieSearchToken;
try {
final url =
'${ServerConfig.vipBaseUrl}/api/movie/detail?vodId=${widget.vodId}&token=$token';
final resp =
await http.get(Uri.parse(url)).timeout(const Duration(seconds: 10));
if (!mounted) return;
if (resp.statusCode == 200) {
final json_ = json.decode(resp.body);
if (json_['code'] == 0 && json_['data'] != null) {
setState(() {
_data = json_['data'];
_loading = false;
});
_loadStaff();
_checkLocal();
return;
}
}
setState(() {
_error = '加载失败';
_loading = false;
});
} catch (_) {
if (mounted)
setState(() {
_error = '网络错误';
_loading = false;
});
}
}
Future<void> _loadStaff() async {
final staffStr = _data?['vod_staff'] ?? '';
if (staffStr.toString().isEmpty) return;
final token = UserPrefs().movieSearchToken;
setState(() {
_staffLoading = true;
});
try {
final url = '${ServerConfig.vipBaseUrl}/api/actor/staff-pic?token=$token';
final resp = await http.post(Uri.parse(url),
body: staffStr.toString(),
headers: {
'Content-Type': 'application/json'
}).timeout(const Duration(seconds: 10));
if (!mounted) return;
if (resp.statusCode == 200) {
final json_ = json.decode(resp.body);
if (json_['code'] == 0 && json_['data'] != null) {
setState(() {
_staffList = (json_['data'] as List)
.map((e) => e as Map<String, dynamic>)
.toList();
_staffLoading = false;
});
return;
}
}
} catch (_) {}
if (mounted)
setState(() {
_staffLoading = false;
});
}
void _checkLocal() {
final name = _data?['vod_name'] ?? '';
if (name.toString().isEmpty) return;
final provider = context.read<AppProvider>();
final match =
provider.movies.where((m) => !m.isDeleted && m.title == name).toList();
if (match.isNotEmpty) {
setState(() {
_localMovie = match.first;
});
}
}
Future<void> _addMovie(String status) async {
final m = _data!;
final name = m['vod_name'] ?? '';
final director = m['vod_director'] ?? '';
final actorStr = m['vod_actor'] ?? '';
final classStr = m['vod_class'] ?? '';
final yearStr = m['vod_year'] ?? '';
final scoreStr = m['vod_score'] ?? '';
final content = m['vod_content'] ?? m['vod_blurb'] ?? '';
final pic = m['vod_pic'] ?? '';
DateTime? releaseDate;
if (yearStr.toString().isNotEmpty) {
releaseDate = DateTime.tryParse('${yearStr}-01-01');
}
final movieId = const Uuid().v4();
String? posterPath;
if (pic.toString().isNotEmpty) {
try {
final resp = await http.get(Uri.parse(pic.toString()), headers: {
'User-Agent': 'Mozilla/5.0'
}).timeout(const Duration(seconds: 15));
if (resp.statusCode == 200 &&
resp.bodyBytes.length < 10 * 1024 * 1024) {
final fileName =
'poster_${DateTime.now().millisecondsSinceEpoch}.jpg';
final targetPath = await ImagePathHelper.instance
.getMoviePosterPath(movieId, fileName);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
await File(targetPath).writeAsBytes(resp.bodyBytes);
posterPath = targetPath;
}
} catch (_) {}
}
final movie = Movie(
id: movieId,
title: name.toString(),
posterPath: posterPath,
releaseDate: releaseDate,
directors: _splitStr(director.toString()),
actors: _splitStr(actorStr.toString()),
genres: _splitStr(classStr.toString()),
summary: content.toString(),
rating: double.tryParse(scoreStr.toString()),
status: status,
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
);
if (!mounted) return;
final provider = context.read<AppProvider>();
await provider.addMovie(movie);
if (mounted) {
setState(() {
_localMovie = provider.movies.firstWhere((m) => m.id == movie.id);
});
ToastUtil.show(context, '已添加到${_statusLabel(status)}');
}
}
List<String> _splitStr(String s) => s
.split(RegExp(r'[,/、]'))
.map((e) => e.trim())
.where((e) => e.isNotEmpty)
.toList();
String _statusLabel(String status) {
switch (status) {
case 'watched':
return '已看';
case 'watching':
return '在看';
case 'want_to_watch':
return '想看';
default:
return '';
}
}
void _showAddSheet() {
final colors = Theme.of(context).colorScheme;
showModalBottomSheet(
context: context,
backgroundColor: colors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
builder: (ctx) => SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 16),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Center(
child: Container(
width: 36,
height: 4,
margin: const EdgeInsets.only(bottom: 14),
decoration: BoxDecoration(
color: colors.onSurface.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(2)))),
Text('添加到',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: colors.onSurface)),
const SizedBox(height: 14),
_sheetItem(
ctx, colors, Icons.check_circle_outline, '已看', 'watched'),
_sheetItem(
ctx, colors, Icons.play_circle_outline, '在看', 'watching'),
_sheetItem(
ctx, colors, Icons.bookmark_outline, '想看', 'want_to_watch'),
]),
),
),
);
}
Widget _sheetItem(BuildContext ctx, ColorScheme colors, IconData icon,
String label, String status) {
return InkWell(
onTap: () {
Navigator.pop(ctx);
_addMovie(status);
},
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
margin: const EdgeInsets.only(bottom: 4),
child: Row(children: [
Icon(icon, size: 22, color: colors.onSurface.withValues(alpha: 0.6)),
const SizedBox(width: 12),
Text(label,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: colors.onSurface)),
]),
),
);
}
// ── Build ──────────────────────────────────────────────
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: colors.surface,
floatingActionButton:
(!_loading && _error == null && _localMovie == null && _data != null)
? FloatingActionButton(
onPressed: _showAddSheet,
backgroundColor: colors.primary,
child: Icon(Icons.add, color: colors.onPrimary))
: null,
body: _loading
? Center(
child: CircularProgressIndicator(
color: colors.primary, strokeWidth: 2))
: _error != null
? _buildError(colors)
: _buildBody(colors),
);
}
Widget _buildError(ColorScheme colors) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline,
size: 48, color: colors.onSurface.withValues(alpha: 0.2)),
const SizedBox(height: 16),
Text(_error!,
style: TextStyle(
fontSize: 14, color: colors.onSurface.withValues(alpha: 0.4))),
const SizedBox(height: 16),
TextButton(
onPressed: () {
setState(() {
_loading = true;
_error = null;
});
_load();
},
child: Text('重试', style: TextStyle(color: colors.primary))),
],
));
}
Widget _buildBody(ColorScheme colors) {
if (_detailStyle == 1) return _buildImmersiveBody(colors);
final m = _data!;
final pic = m['vod_pic'] ?? '';
final name = m['vod_name'] ?? '';
final isEnd = m['vod_isend'] ?? 0;
final year = m['vod_year'] ?? '';
final area = m['vod_area'] ?? '';
final typeName = m['type_name'] ?? '';
final classStr = m['vod_class'] ?? '';
final score = m['vod_score'] ?? '';
final metaParts =
[year, area].where((s) => s.toString().isNotEmpty).join(' · ');
final typeParts =
[typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / ');
return Column(children: [
// 顶部AppBar + 海报信息区
Container(
color: colors.surface,
child: SafeArea(
bottom: false,
child: Column(children: [
// AppBar
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(children: [
GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
shape: BoxShape.circle),
child: Icon(Icons.arrow_back,
size: 20, color: colors.onSurface)),
),
const Spacer(),
GestureDetector(
onTap: () => setState(() => _detailStyle = _detailStyle == 0 ? 1 : 0),
child: Container(
width: 36,
height:36,
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
shape: BoxShape.circle),
child: Icon(
_detailStyle == 0
? Icons.crop_landscape_rounded
: Icons.grid_view_rounded,
size: 18,
color: colors.onSurface)),
),
]),
),
// 海报 + 信息
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 海报
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 120,
height: 170,
child: pic.toString().isNotEmpty
? Image.network(pic,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
_posterPlaceholder(colors))
: _posterPlaceholder(colors),
),
),
const SizedBox(width: 16),
// 信息
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: colors.onSurface)),
const SizedBox(height: 8),
// 评分
if (score.toString().isNotEmpty && score != '0.0') ...[
Row(children: [
Icon(Icons.star_rounded, size: 16, color: const Color(0xFFF59E0B)),
const SizedBox(width: 3),
Text('$score', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
Text(' /10', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
]),
const SizedBox(height: 2),
Text('评分来源于网络资源收集,并非官方评分', style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.25))),
const SizedBox(height: 8),
],
// 完结状态
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(height: 8),
Text(metaParts,
style: TextStyle(
fontSize: 12,
color: colors.onSurface
.withValues(alpha: 0.5))),
],
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 3),
Text(typeParts,
style: TextStyle(
fontSize: 11,
color: colors.onSurface
.withValues(alpha: 0.4)),
maxLines: 1,
overflow: TextOverflow.ellipsis),
],
// 本地状态
if (_localMovie != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
),
]),
),
])),
),
// Tab 栏
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Row(children: [
_buildTabButton('概要', 0),
_buildTabButton('演职人员', 1),
]),
),
// 内容区
Expanded(
child:
_currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors),
),
]);
}
// ── 沉浸式布局 ──────────────────────────────────────────
Widget _buildImmersiveBody(ColorScheme colors) {
final m = _data!;
final pic = m['vod_pic'] ?? '';
final name = m['vod_name'] ?? '';
final isEnd = m['vod_isend'] ?? 0;
final year = m['vod_year'] ?? '';
final area = m['vod_area'] ?? '';
final typeName = m['type_name'] ?? '';
final classStr = m['vod_class'] ?? '';
final score = m['vod_score'] ?? '';
final metaParts = [year, area].where((s) => s.toString().isNotEmpty).join(' · ');
final typeParts = [typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / ');
return Column(children: [
// 全宽海报区
Stack(children: [
// 海报图
SizedBox(
width: double.infinity,
height: 320,
child: pic.toString().isNotEmpty
? Image.network(pic, fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(color: colors.surfaceContainerHighest))
: Container(color: colors.surfaceContainerHighest,
child: Icon(Icons.movie_outlined, size: 64, color: colors.onSurface.withValues(alpha: 0.1))),
),
// 渐变遮罩
Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black.withValues(alpha: 0.8)],
stops: const [0.35, 1.0],
),
),
),
),
// 顶部按钮
SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(children: [
GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.arrow_back, size: 20, color: Colors.white)),
),
const Spacer(),
GestureDetector(
onTap: () => setState(() => _detailStyle = 0),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.grid_view_rounded, size: 18, color: Colors.white)),
),
]),
),
),
// 底部信息叠加
Positioned(
left: 16, right: 16, bottom: 18,
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
Text(name, maxLines: 2, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: Colors.white)),
const SizedBox(height: 8),
Row(children: [
if (score.toString().isNotEmpty && score != '0.0') ...[
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star_rounded, size: 18, color: Colors.amber.shade400),
const SizedBox(width: 3),
Text('$score', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.white)),
],
),
),
const SizedBox(width: 10),
],
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(width: 8),
Text(metaParts, style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.7))),
],
]),
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 4),
Text(typeParts, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.5))),
],
if (_localMovie != null) ...[
const SizedBox(height: 8),
_buildLocalStatus(colors),
],
]),
),
]),
// Tab 栏
Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Row(children: [
_buildTabButton('概要', 0),
_buildTabButton('演职人员', 1),
]),
),
// 内容区
Expanded(
child: _currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors),
),
]);
}
Widget _posterPlaceholder(ColorScheme colors) {
return Container(
color: colors.surfaceContainerHighest,
child: Center(
child: Icon(Icons.movie_outlined,
size: 32, color: colors.onSurface.withValues(alpha: 0.15))));
}
Widget _endTag(int isEnd) {
final finished = isEnd == 1;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: finished
? const Color(0xFF16A34A).withValues(alpha: 0.1)
: const Color(0xFFF59E0B).withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
),
child: Text(finished ? '已完结' : '连载中',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: finished
? const Color(0xFF16A34A)
: const Color(0xFFF59E0B))),
);
}
Widget _buildLocalStatus(ColorScheme colors) {
final status = _localMovie!.status;
final label = _statusLabel(status);
Color dotColor;
switch (status) {
case 'watched':
dotColor = colors.primary;
break;
case 'watching':
dotColor = const Color(0xFF666666);
break;
default:
dotColor = const Color(0xFF999999);
break;
}
return Row(children: [
Container(
width: 6,
height: 6,
decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle)),
const SizedBox(width: 6),
Text('已在本地 · $label',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: colors.onSurface.withValues(alpha: 0.6))),
]);
}
Widget _buildTabButton(String label, int index) {
final colors = Theme.of(context).colorScheme;
final selected = _currentTab == index;
return GestureDetector(
onTap: () => setState(() => _currentTab = index),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 11),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: selected ? colors.primary : Colors.transparent,
width: 2))),
child: Text(label,
style: TextStyle(
fontSize: 13,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
color: selected
? colors.primary
: colors.onSurface.withValues(alpha: 0.4))),
),
);
}
// ── 概要 Tab ──────────────────────────────────────────
Widget _buildOverview(ColorScheme colors) {
final m = _data!;
final isManual = m['is_manual_optimized'] ?? 0;
return ListView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 40),
children: [
// 信息行
_infoRow(colors, '导演', m['vod_director']),
_infoRow(colors, '主演', _formatActors()),
_infoRow(colors, '语言', m['vod_lang']),
_infoRow(colors, '时长', m['vod_duration']),
_infoRow(colors, '上映', m['vod_pubdate']),
const SizedBox(height: 16),
// 标签
if (isManual == 1 || (m['vod_tag'] ?? '').toString().isNotEmpty) ...[
_buildTags(colors),
const SizedBox(height: 16),
],
// 分隔线
Container(height: 0.5, color: colors.outlineVariant),
const SizedBox(height: 16),
// 简介
_buildSynopsis(colors),
],
);
}
Widget _infoRow(ColorScheme colors, String label, dynamic value) {
final text = value?.toString() ?? '';
if (text.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
SizedBox(
width: 44,
child: Text(label,
style: TextStyle(
fontSize: 12,
color: colors.onSurface.withValues(alpha: 0.4)))),
const SizedBox(width: 8),
Expanded(
child: Text(text,
style: TextStyle(
fontSize: 12,
color: colors.onSurface.withValues(alpha: 0.75),
height: 1.5))),
]),
);
}
String _formatActors() {
final staffStr = _data?['vod_staff'] ?? '';
if (staffStr.toString().isNotEmpty) {
try {
final staff = json.decode(staffStr.toString()) as List;
final actors = staff.where((s) => s['position'] == '演员').toList();
if (actors.isNotEmpty) {
return actors.map((s) {
final name = s['name'] ?? '';
final role = s['role'] ?? '';
if (role.toString().isNotEmpty) return '$name$role';
return name;
}).join('');
}
} catch (_) {}
}
return _data?['vod_actor'] ?? '';
}
Widget _buildTags(ColorScheme colors) {
final m = _data!;
final isManual = m['is_manual_optimized'] ?? 0;
final tagStr = m['vod_tag'] ?? '';
final tags =
tagStr.toString().split(',').where((t) => t.trim().isNotEmpty).toList();
return Wrap(
spacing: 6,
runSpacing: 6,
children: [
if (isManual == 1)
_tag('官方优化', const Color(0xFF16A34A), highlight: true),
...tags.map(
(t) => _tag(t.trim(), colors.onSurface.withValues(alpha: 0.5))),
],
);
}
Widget _tag(String text, Color color, {bool highlight = false}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: highlight
? const Color(0xFF16A34A).withValues(alpha: 0.1)
: Colors.transparent,
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: highlight
? const Color(0xFF16A34A).withValues(alpha: 0.3)
: color.withValues(alpha: 0.2),
width: 0.5),
),
child: Text(text,
style: TextStyle(
fontSize: 11,
color: highlight ? const Color(0xFF16A34A) : color)),
);
}
Widget _buildSynopsis(ColorScheme colors) {
final m = _data!;
final blurb = m['vod_blurb'] ?? '';
final content = m['vod_content'] ?? '';
final fullText = content.toString().isNotEmpty
? content.toString().replaceAll(RegExp(r'<[^>]*>'), '')
: blurb.toString();
final isLong = fullText.length > 120;
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
AnimatedCrossFade(
duration: const Duration(milliseconds: 200),
crossFadeState:
_expanded ? CrossFadeState.showSecond : CrossFadeState.showFirst,
firstChild: Text(fullText,
style: TextStyle(
fontSize: 13,
color: colors.onSurface.withValues(alpha: 0.7),
height: 1.8),
maxLines: 4,
overflow: TextOverflow.ellipsis),
secondChild: Text(fullText,
style: TextStyle(
fontSize: 13,
color: colors.onSurface.withValues(alpha: 0.7),
height: 1.8)),
),
if (isLong)
GestureDetector(
onTap: () => setState(() => _expanded = !_expanded),
child: Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_expanded ? '收起' : '展开全文',
style: TextStyle(
fontSize: 12,
color: colors.primary,
fontWeight: FontWeight.w500)),
),
),
]);
}
// ── 演职人员 Tab ──────────────────────────────────────────
Widget _buildStaffTab(ColorScheme colors) {
if (_staffLoading)
return Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2, color: colors.primary)));
if (_staffList.isEmpty)
return Center(
child: Text('暂无演职信息',
style: TextStyle(
fontSize: 13,
color: colors.onSurface.withValues(alpha: 0.35))));
return GridView.builder(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 40),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 14,
childAspectRatio: 0.7),
itemCount: _staffList.length,
itemBuilder: (context, index) =>
_buildStaffCard(colors, _staffList[index]),
);
}
Widget _buildStaffCard(ColorScheme colors, Map<String, dynamic> s) {
final name = s['name'] ?? '';
final position = s['position'] ?? '';
final role = s['role'] ?? '';
final pic = s['actor_pic'] ?? '';
final sub = [position, if (role.toString().isNotEmpty) role].join(' · ');
return Column(children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: double.infinity,
height: 100,
child: pic.toString().isNotEmpty
? Image.network(pic,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
_avatarPlaceholder(colors, name))
: _avatarPlaceholder(colors, name),
),
),
const SizedBox(height: 6),
Text(name,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: colors.onSurface),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center),
const SizedBox(height: 2),
Text(sub,
style: TextStyle(
fontSize: 9, color: colors.onSurface.withValues(alpha: 0.4)),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center),
]);
}
Widget _avatarPlaceholder(ColorScheme colors, String name) {
final ch = name.isNotEmpty ? name.characters.first : '?';
return Container(
color: colors.surfaceContainerHighest,
child: Center(
child: Text(ch,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w600,
color: colors.onSurface.withValues(alpha: 0.25)))),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,525 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/app_provider.dart';
import '../models/data_models.dart';
import 'movies/movie_detail_page.dart';
import 'book/book_detail_page.dart';
import 'note/note_detail_page.dart';
import '../widgets/fade_in_local_image.dart';
/// 搜索页面
class SearchPage extends StatefulWidget {
const SearchPage({super.key});
@override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
final _searchController = TextEditingController();
final _focusNode = FocusNode();
bool _showMovies = true;
bool _showBooks = true;
bool _showNotes = true;
List<_SearchResult> _results = [];
bool _hasSearched = false;
List<String> _matchingTags = [];
String? _selectedTag;
Timer? _debounce;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _focusNode.requestFocus());
}
@override
void dispose() {
_searchController.dispose();
_focusNode.dispose();
_debounce?.cancel();
super.dispose();
}
void _scheduleSearch() {
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 250), _performSearch);
}
void _performSearch() {
final keyword = _searchController.text.trim();
if (keyword.isEmpty) {
setState(() { _results = []; _hasSearched = false; });
return;
}
final provider = context.read<AppProvider>();
final lowerKeyword = keyword.toLowerCase();
final results = <_SearchResult>[];
if (_showMovies) {
for (final movie in provider.movies.where((m) => !m.isDeleted)) {
if (movie.title.toLowerCase().contains(lowerKeyword) ||
movie.alternateTitles.any((t) => t.toLowerCase().contains(lowerKeyword)) ||
(movie.summary?.toLowerCase().contains(lowerKeyword) ?? false) ||
movie.genres.any((g) => g.toLowerCase().contains(lowerKeyword)) ||
movie.directors.any((d) => d.toLowerCase().contains(lowerKeyword)) ||
movie.writers.any((w) => w.toLowerCase().contains(lowerKeyword)) ||
movie.actors.any((a) => a.toLowerCase().contains(lowerKeyword))) {
results.add(_SearchResult(type: 'movie', data: movie));
}
}
}
if (_showBooks) {
for (final book in provider.books.where((b) => !b.isDeleted)) {
if (book.title.toLowerCase().contains(lowerKeyword) ||
book.alternateTitles.any((t) => t.toLowerCase().contains(lowerKeyword)) ||
(book.summary?.toLowerCase().contains(lowerKeyword) ?? false) ||
book.authors.any((a) => a.toLowerCase().contains(lowerKeyword))) {
results.add(_SearchResult(type: 'book', data: book));
}
}
}
if (_showNotes) {
for (final note in provider.notes.where((n) => !n.isDeleted)) {
if (note.title.toLowerCase().contains(lowerKeyword) ||
note.content.toLowerCase().contains(lowerKeyword) ||
note.tags.any((t) => t.toLowerCase().contains(lowerKeyword))) {
results.add(_SearchResult(type: 'note', data: note));
}
}
}
setState(() {
_results = results;
_hasSearched = true;
// 收集匹配的标签
_matchingTags = _collectMatchingTags(lowerKeyword);
_selectedTag = null;
});
}
/// 收集所有包含关键词的标签
List<String> _collectMatchingTags(String lowerKeyword) {
final provider = context.read<AppProvider>();
final tagSet = <String>{};
for (final m in provider.movies.where((m) => !m.isDeleted)) {
for (final g in m.genres) {
if (g.toLowerCase().contains(lowerKeyword)) tagSet.add(g);
}
}
for (final b in provider.books.where((b) => !b.isDeleted)) {
for (final g in b.genres) {
if (g.toLowerCase().contains(lowerKeyword)) tagSet.add(g);
}
}
for (final n in provider.notes.where((n) => !n.isDeleted)) {
for (final t in n.tags) {
if (t.toLowerCase().contains(lowerKeyword)) tagSet.add(t);
}
}
return tagSet.toList()..sort();
}
/// 按标签筛选:点击标签后只显示包含该标签的结果
void _filterByTag(String tag) {
final provider = context.read<AppProvider>();
setState(() {
_selectedTag = tag;
final results = <_SearchResult>[];
for (final m in provider.movies.where((m) => !m.isDeleted)) {
if (m.genres.contains(tag)) results.add(_SearchResult(type: 'movie', data: m));
}
for (final b in provider.books.where((b) => !b.isDeleted)) {
if (b.genres.contains(tag)) results.add(_SearchResult(type: 'book', data: b));
}
for (final n in provider.notes.where((n) => !n.isDeleted)) {
if (n.tags.contains(tag)) results.add(_SearchResult(type: 'note', data: n));
}
_results = results;
});
}
// ═══════════════════════════════════════════════════════════════════
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: colors.surface,
appBar: AppBar(
title: const Text('搜索'),
elevation: 0,
scrolledUnderElevation: 0,
),
body: Column(children: [
_buildSearchBar(),
_buildFilterRow(),
Expanded(
child: _hasSearched
? _results.isEmpty && _matchingTags.isEmpty ? _buildEmptyState() : _buildResultList()
: _buildInitialState(),
),
]),
);
}
Widget _buildSearchBar() {
final colors = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: TextField(
controller: _searchController,
focusNode: _focusNode,
style: TextStyle(fontSize: 15, color: colors.onSurface),
decoration: InputDecoration(
hintText: '搜索标题、作者、标签...',
hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.3), fontSize: 15),
prefixIcon: Icon(Icons.search, color: colors.onSurface.withValues(alpha: 0.4), size: 22),
suffixIcon: _searchController.text.isNotEmpty
? GestureDetector(
onTap: () { _searchController.clear(); setState(() {}); _scheduleSearch(); _focusNode.requestFocus(); },
child: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(14)),
child: Icon(Icons.close, color: colors.onSurface.withValues(alpha: 0.5), size: 16),
),
)
: null,
filled: true, fillColor: colors.surfaceContainerHighest,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide(color: colors.primary, width: 1.5)),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
onSubmitted: (_) { _debounce?.cancel(); _performSearch(); },
onChanged: (_) { _debounce?.cancel(); setState(() {}); _scheduleSearch(); },
),
);
}
Widget _buildFilterRow() {
final colors = Theme.of(context).colorScheme;
final keyword = _searchController.text.trim();
final provider = context.read<AppProvider>();
int movieCount = 0, bookCount = 0, noteCount = 0;
if (keyword.isNotEmpty) {
final kw = keyword.toLowerCase();
movieCount = provider.movies.where((m) => !m.isDeleted && (m.title.toLowerCase().contains(kw) || m.alternateTitles.any((t) => t.toLowerCase().contains(kw)) || (m.summary?.toLowerCase().contains(kw) ?? false) || m.genres.any((g) => g.toLowerCase().contains(kw)) || m.directors.any((d) => d.toLowerCase().contains(kw)) || m.writers.any((w) => w.toLowerCase().contains(kw)) || m.actors.any((a) => a.toLowerCase().contains(kw)))).length;
bookCount = provider.books.where((b) => !b.isDeleted && (b.title.toLowerCase().contains(kw) || b.alternateTitles.any((t) => t.toLowerCase().contains(kw)) || (b.summary?.toLowerCase().contains(kw) ?? false) || b.authors.any((a) => a.toLowerCase().contains(kw)))).length;
noteCount = provider.notes.where((n) => !n.isDeleted && (n.title.toLowerCase().contains(kw) || n.content.toLowerCase().contains(kw) || n.tags.any((t) => t.toLowerCase().contains(kw)))).length;
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Row(children: [
_filterChip('影视', Icons.movie_outlined, _showMovies, movieCount, () { setState(() { _showMovies = !_showMovies; _performSearch(); }); }),
const SizedBox(width: 8),
_filterChip('书籍', Icons.menu_book_outlined, _showBooks, bookCount, () { setState(() { _showBooks = !_showBooks; _performSearch(); }); }),
const SizedBox(width: 8),
_filterChip('笔记', Icons.note_outlined, _showNotes, noteCount, () { setState(() { _showNotes = !_showNotes; _performSearch(); }); }),
]),
);
}
Widget _filterChip(String label, IconData icon, bool selected, int count, VoidCallback onTap) {
final colors = Theme.of(context).colorScheme;
final showCount = _searchController.text.trim().isNotEmpty;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: selected ? colors.primary : colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(icon, size: 14, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4)),
const SizedBox(width: 5),
Text(label, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4))),
if (showCount) ...[const SizedBox(width: 4), Text('$count', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: selected ? colors.onPrimary.withValues(alpha: 0.7) : colors.onSurface.withValues(alpha: 0.25)))],
]),
),
);
}
Widget _buildInitialState() {
final colors = Theme.of(context).colorScheme;
return Center(
child: Column(mainAxisSize: MainAxisSize.min, children: [
Container(
width: 80, height: 80,
decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(20)),
child: Icon(Icons.search_rounded, size: 40, color: colors.onSurface.withValues(alpha: 0.2)),
),
const SizedBox(height: 20),
Text('输入关键词搜索', style: TextStyle(fontSize: 15, color: colors.onSurface.withValues(alpha: 0.35))),
const SizedBox(height: 4),
Text('支持标题、导演、作者、标签、简介', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.2))),
]),
);
}
Widget _buildEmptyState() {
final colors = Theme.of(context).colorScheme;
return Center(
child: Column(mainAxisSize: MainAxisSize.min, children: [
Container(
width: 80, height: 80,
decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(20)),
child: Icon(Icons.search_off_rounded, size: 40, color: colors.onSurface.withValues(alpha: 0.2)),
),
const SizedBox(height: 20),
Text('未找到相关内容', style: TextStyle(fontSize: 15, color: colors.onSurface.withValues(alpha: 0.35))),
const SizedBox(height: 4),
Text('换个关键词试试', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.2))),
]),
);
}
Widget _buildResultList() {
final colors = Theme.of(context).colorScheme;
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
// 标签筛选区
if (_matchingTags.isNotEmpty) _buildTagSection(colors),
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text(_selectedTag != null
? '标签 "$_selectedTag" 共 ${_results.length}'
: '找到 ${_results.length} 条结果',
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.35))),
),
Expanded(
child: _results.isEmpty
? _buildEmptyState()
: ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
itemCount: _results.length,
itemBuilder: (context, index) {
final item = _results[index];
switch (item.type) {
case 'movie': return _buildMovieItem(item.data as Movie);
case 'book': return _buildBookItem(item.data as Book);
case 'note': return _buildNoteItem(item.data as Note);
default: return const SizedBox.shrink();
}
},
),
),
]);
}
Widget _buildTagSection(ColorScheme colors) {
return Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(Icons.label_outline, size: 14, color: colors.onSurface.withValues(alpha: 0.35)),
const SizedBox(width: 4),
Text('匹配标签', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))),
if (_selectedTag != null) ...[
const Spacer(),
GestureDetector(
onTap: () { setState(() { _selectedTag = null; }); _performSearch(); },
child: Text('清除筛选', style: TextStyle(fontSize: 12, color: colors.primary)),
),
],
]),
const SizedBox(height: 6),
Wrap(
spacing: 8,
runSpacing: 6,
children: _matchingTags.map((tag) {
final isSelected = _selectedTag == tag;
return GestureDetector(
onTap: () => _filterByTag(tag),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: isSelected ? colors.primary : colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isSelected ? colors.primary : colors.outline.withValues(alpha: 0.15),
),
),
child: Text(tag, style: TextStyle(
fontSize: 12,
color: isSelected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.6),
)),
),
);
}).toList(),
),
],
),
);
}
Widget _buildMovieItem(Movie movie) {
final colors = Theme.of(context).colorScheme;
return GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => MovieDetailPage(movie: movie))),
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: colors.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)),
child: Row(children: [
_posterThumb(movie.posterPath, Icons.movie_outlined),
const SizedBox(width: 12),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
_typeBadge('影视'),
const Spacer(),
_statusBadge(movie.status, colors),
]),
const SizedBox(height: 6),
Text(movie.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
const SizedBox(height: 4),
Row(children: [
if (movie.rating != null) ...[
Icon(Icons.star, size: 13, color: const Color(0xFFFFB800)),
const SizedBox(width: 2),
Text('${movie.rating}', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: const Color(0xFFFFB800))),
const SizedBox(width: 8),
],
if (movie.genres.isNotEmpty)
Expanded(child: Text(movie.genres.take(2).join(' · '), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35)))),
]),
]),
),
const SizedBox(width: 4),
Icon(Icons.chevron_right, color: colors.onSurface.withValues(alpha: 0.15), size: 18),
]),
),
);
}
Widget _buildBookItem(Book book) {
final colors = Theme.of(context).colorScheme;
return GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => BookDetailPage(book: book))),
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: colors.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)),
child: Row(children: [
_posterThumb(book.coverPath, Icons.menu_book_outlined),
const SizedBox(width: 12),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
_typeBadge('书籍'),
const Spacer(),
_statusBadge(book.status, colors),
]),
const SizedBox(height: 6),
Text(book.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
const SizedBox(height: 4),
Row(children: [
if (book.rating != null) ...[
Icon(Icons.star, size: 13, color: const Color(0xFFFFB800)),
const SizedBox(width: 2),
Text('${book.rating}', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: const Color(0xFFFFB800))),
const SizedBox(width: 8),
],
if (book.authors.isNotEmpty)
Expanded(child: Text(book.authors.take(2).join(' · '), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35)))),
]),
]),
),
const SizedBox(width: 4),
Icon(Icons.chevron_right, color: colors.onSurface.withValues(alpha: 0.15), size: 18),
]),
),
);
}
Widget _buildNoteItem(Note note) {
final colors = Theme.of(context).colorScheme;
final summary = note.summary.trim().isEmpty ? '(无内容)' : note.summary.trim();
return GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => NoteDetailPage(note: note))),
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: colors.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: const EdgeInsets.only(top: 2),
child: _typeBadge('笔记'),
),
const SizedBox(width: 10),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(summary, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.5)),
if (note.tags.isNotEmpty) ...[
const SizedBox(height: 8),
Wrap(spacing: 6, runSpacing: 4, children: note.tags.map((t) => Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(color: colors.surface, borderRadius: BorderRadius.circular(4)),
child: Text(t, style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.4))),
)).toList()),
],
]),
),
const SizedBox(width: 4),
Padding(
padding: const EdgeInsets.only(top: 2),
child: Icon(Icons.chevron_right, color: colors.onSurface.withValues(alpha: 0.15), size: 18),
),
]),
),
);
}
Widget _posterThumb(String? path, IconData fallback) {
final colors = Theme.of(context).colorScheme;
return Container(
width: 44, height: 58,
decoration: BoxDecoration(color: colors.outlineVariant, borderRadius: BorderRadius.circular(6)),
clipBehavior: Clip.antiAlias,
child: path != null && path.isNotEmpty
? FadeInLocalImage(path: path, fit: BoxFit.cover,
errorWidget: Icon(fallback, size: 20, color: colors.onSurface.withValues(alpha: 0.25)))
: Icon(fallback, size: 20, color: colors.onSurface.withValues(alpha: 0.25)),
);
}
Widget _typeBadge(String label) {
final colors = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(color: colors.primary.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(4)),
child: Text(label, style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: colors.primary)),
);
}
Widget _statusBadge(String status, ColorScheme colors) {
final (label, bg, fg) = switch (status) {
'watched' || 'read' => ('已看' , colors.primary, colors.onPrimary),
'watching' || 'reading' => ('在看', colors.outlineVariant, colors.onSurface.withValues(alpha: 0.6)),
'want_to_watch' || 'want_to_read' => ('想看', colors.surfaceContainerHighest, colors.onSurface.withValues(alpha: 0.4)),
_ => ('', colors.surfaceContainerHighest, colors.onSurface.withValues(alpha: 0.3)),
};
if (label.isEmpty) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(4)),
child: Text(label, style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: fg)),
);
}
}
class _SearchResult {
final String type;
final dynamic data;
_SearchResult({required this.type, required this.data});
}