pk_view.dart 23.6 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 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
import 'dart:math' as math;

import 'package:doublefeel_flutter/app/widget/friend_interact_click_view.dart';
import 'package:doublefeel_flutter/data/models/interaction/interaction_models.dart';
import 'package:flutter/material.dart';

import '../../report_common/widgets/report_bottom_slogan.dart';
import '../models/pk_data.dart';

const _purple = Color(0xFF845EEE);
const _orange = Color(0xFFFF8D5B);
const _muted = Color(0xFFB0B0B6);

/// Standalone PK content, shared by the home tab and design previews.
class PkView extends StatelessWidget {
  const PkView({
    super.key,
    required this.data,
    this.onSwitchFriend,
    this.onBack,
    this.onPoke,
    this.onRefresh,
    this.friendUserId,
    this.loadFailed = false,
  });

  final PkData data;
  final bool loadFailed;
  final VoidCallback? onSwitchFriend, onBack;
  final ValueChanged<String>? onPoke;
  final Future<void> Function()? onRefresh;
  final int? friendUserId;

  @override
  Widget build(BuildContext context) {
    final content = ListView(
      key: const PageStorageKey('pk-scroll'),
      physics: const AlwaysScrollableScrollPhysics(),
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 88),
      children: [
        if (loadFailed)
          TextButton(onPressed: onRefresh, child: const Text('数据刷新失败,点击重试')),
        _TodayCard(data: data, onPoke: onPoke, friendUserId: friendUserId),
        const SizedBox(height: 12),
        _MonthCard(data: data, onPoke: onPoke, friendUserId: friendUserId),
        const ReportBottomSlogan(topSpacing: 24),
      ],
    );
    return ColoredBox(
      color: const Color(0xFFF5F2FF),
      child: Stack(
        children: [
          Container(
            height: 300,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFC5B0FF), Color(0xFFF5F2FF)],
              ),
            ),
          ),
          SafeArea(
            bottom: false,
            child: Column(
              children: [
                SizedBox(
                  height: 44,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      const Text(
                        '今日健康PK',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      if (onBack != null)
                        Align(
                          alignment: Alignment.centerLeft,
                          child: IconButton(
                            onPressed: onBack,
                            icon: const Icon(
                              Icons.arrow_back_ios_new_rounded,
                              size: 20,
                            ),
                          ),
                        ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          tooltip: '切换好友',
                          onPressed: onSwitchFriend,
                          icon: Image.asset(
                            'assets/images/common/ic_replace.png',
                            width: 20,
                            height: 20,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: onRefresh == null
                      ? content
                      : RefreshIndicator(onRefresh: onRefresh!, child: content),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Widget _asset(String name, double width, double height) => Image.asset(
  'assets/images/pk/$name.png',
  width: width,
  height: height,
  fit: BoxFit.fill,
);

class _Avatar extends StatelessWidget {
  const _Avatar(this.player, {this.size = 64, this.result});

  final PkPlayer player;
  final double size;
  final PkResult? result;

  @override
  Widget build(BuildContext context) => SizedBox(
    width: size + 8,
    height: size + 26,
    child: Stack(
      clipBehavior: Clip.none,
      alignment: Alignment.bottomCenter,
      children: [
        Container(
          width: size,
          height: size,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: result == PkResult.win
                  ? const Color(0xFFFFD453)
                  : Colors.white,
              width: 2,
            ),
          ),
          child: ClipOval(
            child: player.avatarAsset != null
                ? Image.asset(player.avatarAsset!, fit: BoxFit.cover)
                : player.avatarUrl?.isNotEmpty == true
                ? Image.network(
                    player.avatarUrl!,
                    fit: BoxFit.cover,
                    errorBuilder: (_, __, ___) =>
                        const Icon(Icons.person, color: _purple),
                  )
                : const ColoredBox(
                    color: Color(0xFFE7DFFF),
                    child: Icon(Icons.person, color: _purple),
                  ),
          ),
        ),
        if (result == PkResult.win)
          Positioned(top: 0, child: _asset('crown', size * .5, size * .5)),
        if (result != null)
          Positioned(
            right: 0,
            bottom: -2,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 2),
              decoration: BoxDecoration(
                color: switch (result!) {
                  PkResult.win => const Color(0xFFFF657A),
                  PkResult.loss => const Color(0xFF5496E8),
                  PkResult.draw => const Color(0xFF78787D),
                },
                borderRadius: BorderRadius.circular(3),
              ),
              child: Text(
                switch (result!) {
                  PkResult.win => '胜',
                  PkResult.loss => '负',
                  PkResult.draw => '平',
                },
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  height: 1.1,
                ),
              ),
            ),
          ),
      ],
    ),
  );
}

PkResult? _opposite(PkResult? result) => switch (result) {
  PkResult.win => PkResult.loss,
  PkResult.loss => PkResult.win,
  _ => result,
};

class _TodayCard extends StatelessWidget {
  const _TodayCard({required this.data, this.onPoke, this.friendUserId});

  final PkData data;
  final ValueChanged<String>? onPoke;
  final int? friendUserId;

  @override
  Widget build(BuildContext context) => Column(
    children: [
      SizedBox(
        height: 144,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final width = constraints.maxWidth;
            return Stack(
              clipBehavior: Clip.none,
              children: [
                Positioned(
                  left: 0,
                  top: 40,
                  child: _asset('left_banner', width * .55, 99),
                ),
                Positioned(
                  right: 0,
                  top: 40,
                  child: RotatedBox(
                    quarterTurns: 2,
                    child: _asset('right_banner', width * .55, 99),
                  ),
                ),
                Positioned(
                  left: 0,
                  top: 0,
                  width: width * .373,
                  child: _PlayerHeader(data.left, data.result),
                ),
                Positioned(
                  right: 0,
                  top: 0,
                  width: width * .373,
                  child: _PlayerHeader(data.right, _opposite(data.result)),
                ),
                Positioned(
                  left: (width - 43) / 2,
                  top: 68,
                  child: Container(
                    width: 43,
                    height: 43,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: const Color(0xFFFFC321),
                      border: Border.all(color: Colors.white, width: 2),
                    ),
                    child: const Text(
                      'VS',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
      Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Column(
          children: [
            _ScoreBar(left: data.left.score, right: data.right.score),
            _MetricRow(
              label: '今日步数',
              icon: 'steps',
              unit: '步',
              left: data.left.steps?.toString(),
              right: data.right.steps?.toString(),
              onPoke: onPoke,
              interactionContext: _interactionContext(
                FriendInteractionType.pkSteps,
              ),
            ),
            _MetricRow(
              label: '活动记录',
              icon: 'calories',
              unit: '大卡',
              left: data.left.calories?.toString(),
              right: data.right.calories?.toString(),
              onPoke: onPoke,
              interactionContext: _interactionContext(
                FriendInteractionType.pkCalories,
              ),
            ),
            _MetricRow(
              label: '站立时间',
              icon: 'standing',
              unit: '小时',
              left: data.left.standingHours?.toStringAsFixed(1),
              right: data.right.standingHours?.toStringAsFixed(1),
              onPoke: onPoke,
              interactionContext: _interactionContext(
                FriendInteractionType.pkStandCount,
              ),
            ),
          ],
        ),
      ),
    ],
  );

  FriendInteractionContext? _interactionContext(FriendInteractionType type) {
    final userId = friendUserId;
    if (userId == null) return null;
    return FriendInteractionContext(
      friendUserId: userId,
      type: type,
      avatarUrl: data.left.avatarUrl,
    );
  }
}

class _PlayerHeader extends StatelessWidget {
  const _PlayerHeader(this.player, this.result);

  final PkPlayer player;
  final PkResult? result;

  @override
  Widget build(BuildContext context) => Column(
    children: [
      _Avatar(player, result: result),
      const SizedBox(height: 4),
      Text(
        player.name,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
      Text(
        player.subtitle,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(color: Color(0x99FFFFFF), fontSize: 12),
      ),
    ],
  );
}

class _ScoreBar extends StatelessWidget {
  const _ScoreBar({this.left, this.right});

  final int? left, right;

  @override
  Widget build(BuildContext context) {
    final fraction = left == null || right == null || left! + right! <= 0
        ? .5
        : (left! / (left! + right!)).clamp(.18, .82);
    return SizedBox(
      height: 24,
      child: LayoutBuilder(
        builder: (context, constraints) => Stack(
          alignment: Alignment.center,
          clipBehavior: Clip.none,
          children: [
            Container(
              height: 24,
              decoration: BoxDecoration(
                color: _orange,
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: Colors.white, width: 2),
              ),
              clipBehavior: Clip.antiAlias,
              child: Row(
                children: [
                  SizedBox(
                    width: (constraints.maxWidth - 4) * fraction,
                    child: const ColoredBox(
                      color: _purple,
                      child: SizedBox.expand(),
                    ),
                  ),
                ],
              ),
            ),
            Positioned.fill(
              child: Padding(
                padding: const EdgeInsets.all(2),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Opacity(
                    opacity: .16,
                    child: Image.asset(
                      'assets/images/pk/score_stripes.png',
                      repeat: ImageRepeat.repeatX,
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              left: constraints.maxWidth * fraction - 8,
              child: _asset('lightning', 17, 28),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    left?.toString() ?? '--',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    right?.toString() ?? '--',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _PokeButton extends StatelessWidget {
  const _PokeButton({this.onTap, this.interactionContext});

  final VoidCallback? onTap;
  final FriendInteractionContext? interactionContext;

  @override
  Widget build(BuildContext context) => SizedBox(
    width: 32,
    height: 40,
    child: Center(
      child: interactionContext == null
          ? IconButton(
              tooltip: '戳一戳',
              onPressed: onTap,
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(minWidth: 32, minHeight: 40),
              icon: Opacity(
                opacity: onTap == null ? .45 : 1,
                child: _asset('poke', 24, 24),
              ),
            )
          : FriendInteractClickView(interactionContext: interactionContext),
    ),
  );
}

class _MetricRow extends StatelessWidget {
  const _MetricRow({
    required this.label,
    required this.icon,
    required this.unit,
    this.left,
    this.right,
    this.onPoke,
    this.interactionContext,
  });

  final String label, icon, unit;
  final String? left, right;
  final ValueChanged<String>? onPoke;
  final FriendInteractionContext? interactionContext;

  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
    child: Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                _asset(icon, 20, 20),
                const SizedBox(width: 4),
                _label(label),
              ],
            ),
            Row(
              children: [
                _label(label),
                const SizedBox(width: 4),
                _asset(icon, 20, 20),
              ],
            ),
          ],
        ),
        const SizedBox(height: 20),
        Row(
          children: [
            Expanded(
              child: Row(
                children: [
                  Expanded(child: _value(left)),
                  _PokeButton(
                    onTap: onPoke == null ? null : () => onPoke!(icon),
                    interactionContext: interactionContext,
                  ),
                ],
              ),
            ),
            Container(
              width: 1,
              height: 24,
              color: const Color(0xFFD9D9D9),
              margin: const EdgeInsets.symmetric(horizontal: 20),
            ),
            Expanded(child: _value(right)),
          ],
        ),
      ],
    ),
  );

  Widget _label(String text) => Text(
    text,
    style: const TextStyle(color: Color(0xFF78787D), fontSize: 12),
  );

  Widget _value(String? value) => FittedBox(
    fit: BoxFit.scaleDown,
    alignment: Alignment.centerLeft,
    child: Text.rich(
      TextSpan(
        children: [
          TextSpan(
            text: value ?? '--',
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w600,
              color: Color(0xFF0F0F11),
            ),
          ),
          TextSpan(
            text: ' $unit',
            style: const TextStyle(fontSize: 12, color: Color(0xFF78787D)),
          ),
        ],
      ),
    ),
  );
}

class _MonthCard extends StatelessWidget {
  const _MonthCard({required this.data, this.onPoke, this.friendUserId});

  final PkData data;
  final ValueChanged<String>? onPoke;
  final int? friendUserId;

  @override
  Widget build(BuildContext context) {
    final offset = DateTime(data.month.year, data.month.month).weekday - 1;
    final count = DateTime(data.month.year, data.month.month + 1, 0).day;
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        children: [
          Row(
            children: [
              const Expanded(
                child: Text(
                  '本月胜率',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ),
              _PokeButton(
                onTap: onPoke == null ? null : () => onPoke!('monthly'),
                interactionContext: _interactionContext,
              ),
            ],
          ),
          SizedBox(
            height: 166,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    _Podium(data.left, data.monthlyResult, _purple),
                    _Podium(data.right, _opposite(data.monthlyResult), _orange),
                  ],
                ),
                if (data.monthlyResult == PkResult.draw)
                  Positioned(
                    top: 65,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 2,
                      ),
                      decoration: BoxDecoration(
                        color: const Color(0xFF78787D),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Text(
                        '平局',
                        style: TextStyle(fontSize: 12, color: Colors.white),
                      ),
                    ),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          Row(
            children: ['一', '二', '三', '四', '五', '六', '日']
                .map(
                  (day) => Expanded(
                    child: Center(
                      child: Text(
                        day,
                        style: const TextStyle(color: _muted, fontSize: 12),
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
          const SizedBox(height: 12),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            itemCount: ((offset + count + 6) ~/ 7) * 7,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 7,
              mainAxisExtent: 66,
            ),
            itemBuilder: (context, index) {
              final day = index - offset + 1;
              if (day < 1 || day > count) return const SizedBox.shrink();
              final result = data.days[day];
              return Semantics(
                label:
                    '${data.month.month}$day${result == null ? ',暂无数据' : ',${result.leftScore}${result.rightScore}'}',
                child: Column(
                  children: [
                    CustomPaint(
                      size: const Size(28, 28),
                      painter: _DayPainter(result?.leftFraction),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '$day',
                      style: const TextStyle(fontSize: 10, color: _muted),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  FriendInteractionContext? get _interactionContext {
    final userId = friendUserId;
    if (userId == null) return null;
    return FriendInteractionContext(
      friendUserId: userId,
      type: FriendInteractionType.pkMonthlyResult,
      avatarUrl: data.left.avatarUrl,
    );
  }
}

class _Podium extends StatelessWidget {
  const _Podium(this.player, this.result, this.color);

  final PkPlayer player;
  final PkResult? result;
  final Color color;

  @override
  Widget build(BuildContext context) {
    final height = result == PkResult.win ? 82.0 : 50.0;
    return SizedBox(
      width: 85,
      height: 166,
      child: Stack(
        alignment: Alignment.center,
        clipBehavior: Clip.none,
        children: [
          Positioned(
            bottom: 40,
            child: _asset(
              color == _purple ? 'podium_winner' : 'podium_loser',
              85,
              height,
            ),
          ),
          Positioned(
            bottom: height + 10,
            child: _Avatar(
              player,
              size: 48,
              result: result == PkResult.win ? result : null,
            ),
          ),
          Positioned(
            bottom: 20,
            child: Text(
              player.winningDays?.toString() ?? '--',
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
            ),
          ),
          const Positioned(
            bottom: 0,
            child: Text('胜利天数', style: TextStyle(fontSize: 12)),
          ),
        ],
      ),
    );
  }
}

class _DayPainter extends CustomPainter {
  const _DayPainter(this.fraction);

  final double? fraction;

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Offset.zero & size;
    final paint = Paint();
    if (fraction == null) {
      paint
        ..color = const Color(0xFFD9D9D9)
        ..style = PaintingStyle.stroke
        ..strokeWidth = .8;
      for (var i = 0; i < 28; i++) {
        canvas.drawArc(
          rect.deflate(1),
          i * math.pi / 14,
          math.pi / 28,
          false,
          paint,
        );
      }
    } else {
      canvas.drawOval(rect, paint..color = _orange);
      canvas.drawArc(
        rect,
        -math.pi / 2,
        -2 * math.pi * fraction!.clamp(0, 1),
        true,
        paint..color = _purple,
      );
    }
  }

  @override
  bool shouldRepaint(_DayPainter oldDelegate) =>
      oldDelegate.fraction != fraction;
}