today_tab.dart 19.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
import 'package:doublefeel_flutter/core/services/user_state_service.dart';
import 'package:doublefeel_flutter/core/theme/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../controllers/home_controller.dart';
import '../../controllers/today_controller.dart';
import '../../widgets/today/today_health_data_auth_card.dart';
import '../../widgets/today/today_hrv_ad_banner.dart';
import '../../widgets/today/today_hrv_number_card.dart';
import '../../widgets/today/today_hrv_chart_card.dart';
import '../../widgets/today/today_sleep_activity_cards.dart';

import '../../widgets/today/premium_card.dart';

class TodayTab extends StatefulWidget {
  const TodayTab({super.key});

  @override
  State<TodayTab> createState() => _TodayTabState();
}

class _TodayTabState extends State<TodayTab> {
  static const _bgColor = Color(0xFFF2F2F7);
  static const _topBarHeight = 48.0;
  static const _weekCalendarHeight = 58.0;
  static const _topContentHeight = _topBarHeight + _weekCalendarHeight;
  static const _weekRowsHeight = 50.0;
  static const _selectedDayWidth = 32.0;

  final TodayController controller = Get.find<TodayController>();
  final HomeController homeController = Get.find<HomeController>();
  late final DateTime _firstSelectableDay;
  late final DateTime _lastSelectableDay;
  late final int _dayPageCount;
  late final PageController _pageController;
  late final Worker _selectedDateWorker;
  late DateTime _focusedDay;
  final ValueNotifier<double> _scrollOffset = ValueNotifier<double>(0);

  @override
  void initState() {
    super.initState();
    final today = DateUtils.dateOnly(DateTime.now());
    _firstSelectableDay = DateTime(today.year - 1);
    _lastSelectableDay = today;
    _dayPageCount =
        _lastSelectableDay.difference(_firstSelectableDay).inDays + 1;

    final initialSelectedDay =
        _clampSelectableDay(homeController.selectedDate.value);
    _focusedDay = initialSelectedDay;
    homeController.changeDate(initialSelectedDay);
    _pageController = PageController(
      initialPage: _pageIndexForDay(initialSelectedDay),
    );
    _selectedDateWorker = ever<DateTime>(
      homeController.selectedDate,
      _handleSelectedDateChanged,
    );
  }

  @override
  void dispose() {
    _selectedDateWorker.dispose();
    _pageController.dispose();
    _scrollOffset.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final topPadding = MediaQuery.paddingOf(context).top;
    final pinnedHeaderHeight = topPadding + _topContentHeight;

    return Container(
      color: _bgColor,
      child: Stack(
        children: [
          NotificationListener<ScrollNotification>(
            onNotification: _handleScrollNotification,
            child: PageView.builder(
              controller: _pageController,
              itemCount: _dayPageCount,
              onPageChanged: _onDayPageChanged,
              itemBuilder: (context, index) {
                return _buildDayScrollView(context, pinnedHeaderHeight);
              },
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: pinnedHeaderHeight,
            child: ValueListenableBuilder<double>(
              valueListenable: _scrollOffset,
              builder: (context, offset, child) {
                final opacity =
                    (offset / _topContentHeight).clamp(0.0, 1).toDouble();

                return Container(
                  color: const Color(0xFFDDD2FF).withValues(alpha: opacity),
                );
              },
            ),
          ),
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Obx(
              () => Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _TopDateBar(
                    title: _dateTitle,
                    showBackToToday: !_isSelectedToday,
                    onBackToToday: _backToToday,
                  ),
                  _buildWeekCalendar(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDayScrollView(
    BuildContext context,
    double pinnedHeaderHeight,
  ) {
    return CustomScrollView(
      primary: false,
      physics: const ClampingScrollPhysics(),
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            height: 323 + pinnedHeaderHeight,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFFC5B0FF),
                  Color(0xFFF5F2FF),
                ],
              ),
            ),
            child: Container(
              margin: EdgeInsets.only(top: pinnedHeaderHeight),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Obx(
                    () => Text(
                      controller.stressSubtitle.value,
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        color: Color(0xFF78787D),
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  Obx(
                    () => Text(
                      controller.stressLabel.value,
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        color: Color(0xFF0F0F11),
                        fontSize: 28,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverList(
            delegate: SliverChildListDelegate([
              Obx(
                () => controller.showHealthDataAuthCard.value
                    ? TodayHealthDataAuthCard(
                        onAuthorizeTap: controller.requestHealthAuthorization,
                      )
                    : const SizedBox.shrink(),
              ),
              Obx(() {
                return Get.find<UserStateService>().isVip
                    ? const SizedBox.shrink()
                    : const PremiumCard();
              }),
              const TodayHrvAdBanner(),
              const TodayPartnerAdBanner(),
              const TodayHrvNumberCard(),
              const SizedBox(height: 12),
              const TodayHrvChartCard(),
              const SizedBox(height: 12),
              const TodaySleepCard(),
              const TodayActivityCard(),
              const SizedBox(height: 4),
              Container(
                padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: const Text(
                  '立即测量HRV',
                  style: TextStyle(
                    color: Color(0xFF0F0F11),
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                  bottom: 16 + MediaQuery.paddingOf(context).bottom,
                  top: 28,
                ),
                child: Image.asset(
                  'assets/images/common/ic_bottom_slogan.png',
                  width: 223,
                  height: 35,
                ),
              ),
            ]),
          ),
        ),
      ],
    );
  }

  Widget _buildWeekCalendar() {
    return SizedBox(
      height: _weekCalendarHeight,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(13, 4, 18, 4),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: SizedBox(
                height: _weekRowsHeight,
                child: TableCalendar(
                  calendarFormat: CalendarFormat.week,
                  headerVisible: false,
                  daysOfWeekHeight: _weekRowsHeight / 2,
                  rowHeight: _weekRowsHeight / 2,
                  focusedDay: _focusedDay,
                  firstDay: _firstSelectableDay,
                  lastDay: _lastSelectableDay,
                  currentDay: _lastSelectableDay,
                  startingDayOfWeek: StartingDayOfWeek.monday,
                  availableCalendarFormats: const {
                    CalendarFormat.week: '',
                  },
                  availableGestures: AvailableGestures.horizontalSwipe,
                  enabledDayPredicate: (day) => !_isAfterToday(day),
                  selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                  onDaySelected: _onDaySelected,
                  onPageChanged: _onCalendarPageChanged,
                  calendarStyle: const CalendarStyle(
                    cellMargin: EdgeInsets.zero,
                    cellPadding: EdgeInsets.zero,
                    isTodayHighlighted: false,
                    outsideDaysVisible: true,
                  ),
                  daysOfWeekStyle: const DaysOfWeekStyle(
                    decoration: BoxDecoration(),
                  ),
                  calendarBuilders: CalendarBuilders(
                    dowBuilder: (context, day) => _buildWeekdayCell(day),
                    defaultBuilder: (context, day, focusedDay) =>
                        _buildDateCell(day),
                    disabledBuilder: (context, day, focusedDay) =>
                        _buildDateCell(day),
                    outsideBuilder: (context, day, focusedDay) =>
                        _buildDateCell(day),
                    selectedBuilder: (context, day, focusedDay) =>
                        _buildDateCell(day, selected: true),
                  ),
                ),
              ),
            ),
            const SizedBox(width: 3),
            Container(
              width: 1,
              height: 20,
              margin: const EdgeInsets.only(top: 15),
              color: context.colors.textPrimary.withValues(alpha: 0.2),
            ),
            const SizedBox(width: 12),
            Padding(
              padding: const EdgeInsets.only(top: 15),
              child: Image.asset(
                'assets/images/common/ic_calendar.png',
                width: 20,
                height: 20,
                color: context.colors.textPrimary.withValues(alpha: 0.6),
              ),
            ),
          ],
        ),
      ),
    );
  }

  bool _handleScrollNotification(ScrollNotification notification) {
    if (notification.metrics.axis != Axis.vertical) return false;

    final offset = notification.metrics.pixels.clamp(0.0, double.infinity);
    if (_scrollOffset.value != offset) {
      _scrollOffset.value = offset.toDouble();
    }
    return false;
  }

  Widget _buildWeekdayCell(DateTime day) {
    final selected = isSameDay(_selectedDay, day);

    return Center(
      child: Container(
        width: _selectedDayWidth,
        height: _weekRowsHeight / 2,
        alignment: Alignment.center,
        decoration: selected
            ? BoxDecoration(
                color: context.colors.primary,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(22),
                ),
              )
            : null,
        child: Text(
          isSameDay(day, _lastSelectableDay) ? '今' : _weekdayText(day),
          style: TextStyle(
            color: _calendarTextColor(day, selected: selected),
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Widget _buildDateCell(DateTime day, {bool selected = false}) {
    return Center(
      child: Container(
        width: _selectedDayWidth,
        height: _weekRowsHeight / 2,
        alignment: Alignment.center,
        decoration: selected
            ? BoxDecoration(
                color: context.colors.primary,
                borderRadius: BorderRadius.vertical(
                  bottom: Radius.circular(22),
                ),
              )
            : null,
        child: Text(
          '${day.day}',
          style: TextStyle(
            color: _calendarTextColor(day, selected: selected),
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  void _handleSelectedDateChanged(DateTime selectedDate) {
    final normalizedDay = _clampSelectableDay(selectedDate);
    if (selectedDate != normalizedDay) {
      homeController.changeDate(normalizedDay);
      return;
    }

    if (mounted) {
      setState(() {
        _focusedDay = normalizedDay;
      });
    }
    _syncPagerToSelectedDay(normalizedDay);
  }

  void _onDayPageChanged(int page) {
    _selectDate(_dateForPage(page));
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    _selectDate(selectedDay, focusedDay: focusedDay);
  }

  void _onCalendarPageChanged(DateTime focusedDay) {
    final selectedWeekdayOffset = _selectedDay.weekday - DateTime.monday;
    final nextSelectedDay = _weekStart(focusedDay).add(
      Duration(days: selectedWeekdayOffset),
    );
    _selectDate(nextSelectedDay, focusedDay: focusedDay);
  }

  void _backToToday() {
    _selectDate(_lastSelectableDay);
  }

  void _selectDate(DateTime selectedDay, {DateTime? focusedDay}) {
    final normalizedSelectedDay = _clampSelectableDay(selectedDay);
    final normalizedFocusedDay = _clampSelectableDay(
      focusedDay ?? normalizedSelectedDay,
    );

    setState(() {
      _focusedDay = normalizedFocusedDay;
    });
    homeController.changeDate(normalizedSelectedDay);
  }

  void _syncPagerToSelectedDay(DateTime selectedDay) {
    final targetPage = _pageIndexForDay(selectedDay);
    if (!_pageController.hasClients) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        _syncPagerToSelectedDay(selectedDay);
      });
      return;
    }

    final currentPage =
        _pageController.page?.round() ?? _pageController.initialPage;
    if (currentPage == targetPage) return;

    _pageController.animateToPage(
      targetPage,
      duration: const Duration(milliseconds: 220),
      curve: Curves.easeOut,
    );
  }

  DateTime _dateForPage(int page) {
    return _firstSelectableDay.add(Duration(days: page));
  }

  int _pageIndexForDay(DateTime day) {
    final dayIndex =
        _clampSelectableDay(day).difference(_firstSelectableDay).inDays;
    return dayIndex.clamp(0, _dayPageCount - 1).toInt();
  }

  DateTime _clampSelectableDay(DateTime day) {
    final normalizedDay = DateUtils.dateOnly(day);
    if (normalizedDay.isBefore(_firstSelectableDay)) return _firstSelectableDay;
    if (normalizedDay.isAfter(_lastSelectableDay)) return _lastSelectableDay;
    return normalizedDay;
  }

  DateTime _weekStart(DateTime day) {
    final normalizedDay = DateUtils.dateOnly(day);
    return normalizedDay.subtract(Duration(days: normalizedDay.weekday - 1));
  }

  DateTime get _selectedDay =>
      _clampSelectableDay(homeController.selectedDate.value);

  String get _dateTitle {
    final today = _lastSelectableDay;
    if (isSameDay(_selectedDay, today)) return '今日';
    if (isSameDay(_selectedDay, today.subtract(const Duration(days: 1)))) {
      return '昨日';
    }
    if (isSameDay(_selectedDay, today.add(const Duration(days: 1)))) {
      return '明日';
    }
    return '${_selectedDay.month}${_selectedDay.day}日';
  }

  bool get _isSelectedToday => isSameDay(_selectedDay, _lastSelectableDay);

  bool _isAfterToday(DateTime day) {
    final normalizedDay = DateUtils.dateOnly(day);
    return normalizedDay.isAfter(_lastSelectableDay);
  }

  Color _calendarTextColor(DateTime day, {required bool selected}) {
    if (selected) return Colors.white;
    return context.colors.textPrimary
        .withValues(alpha: _isAfterToday(day) ? 0.2 : 0.6);
  }

  String _weekdayText(DateTime day) {
    switch (day.weekday) {
      case DateTime.monday:
        return '一';
      case DateTime.tuesday:
        return '二';
      case DateTime.wednesday:
        return '三';
      case DateTime.thursday:
        return '四';
      case DateTime.friday:
        return '五';
      case DateTime.saturday:
        return '六';
      case DateTime.sunday:
      default:
        return '日';
    }
  }
}

class _TopDateBar extends StatelessWidget {
  const _TopDateBar({
    required this.title,
    required this.showBackToToday,
    required this.onBackToToday,
  });

  final String title;
  final bool showBackToToday;
  final VoidCallback onBackToToday;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: _TodayTabState._topBarHeight,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Text(
              title,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: context.colors.textPrimary,
                fontSize: 24,
                fontWeight: FontWeight.w600,
              ),
            ),
            if (showBackToToday) ...[
              const SizedBox(width: 12),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: onBackToToday,
                child: SizedBox(
                  height: 24,
                  child: Row(
                    children: [
                      Image.asset(
                        'assets/images/common/ic_back_to_today.png',
                        width: 12,
                        height: 12,
                        color: context.colors.primary,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '回今天',
                        style: TextStyle(
                          color: context.colors.primary,
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
            const Spacer(),
            Obx(() {
              return Get.find<UserStateService>().isVip
                  ? const SizedBox.shrink()
                  : Container(
                      height: 29,
                      constraints: const BoxConstraints(minWidth: 95),
                      padding: const EdgeInsets.symmetric(horizontal: 7),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFFDF51),
                        borderRadius: BorderRadius.circular(27.6),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            'assets/images/common/ic_pro.png',
                            width: 20,
                            height: 20,
                            color: context.colors.textPrimary,
                          ),
                          const SizedBox(width: 2),
                          Text(
                            '20%优惠',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: context.colors.textPrimary,
                            ),
                          ),
                        ],
                      ),
                    );
            }),
          ],
        ),
      ),
    );
  }
}