diff --git a/gui/components/mousewheel_guard.py b/gui/components/mousewheel_guard.py new file mode 100644 index 0000000..e72d266 --- /dev/null +++ b/gui/components/mousewheel_guard.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import tkinter as tk + + +def disable_spinbox_mousewheel(root: tk.Misc) -> None: + def block_spinbox_wheel(_event: tk.Event) -> str: + return "break" + + for class_name in ("Spinbox", "TSpinbox"): + for sequence in ("", "", "", ""): + try: + root.bind_class(class_name, sequence, block_spinbox_wheel) + except Exception: + pass diff --git a/gui/components/root_window.py b/gui/components/root_window.py index 1e254f5..a3b1b13 100644 --- a/gui/components/root_window.py +++ b/gui/components/root_window.py @@ -13,6 +13,8 @@ import tkinter as tk from dataclasses import dataclass from typing import Any, Callable +from gui.components.mousewheel_guard import disable_spinbox_mousewheel + @dataclass class RootBundle: @@ -50,4 +52,5 @@ def setup_root_window( root.title(title) root.geometry(geometry) + disable_spinbox_mousewheel(root) return RootBundle(root=root, ScrolledText=ScrolledText) diff --git a/gui/dashboard_app/app.py b/gui/dashboard_app/app.py index 2406642..f1397c1 100644 --- a/gui/dashboard_app/app.py +++ b/gui/dashboard_app/app.py @@ -6,6 +6,7 @@ from tkinter import ttk from douyin.core.version import print_version_banner from gui.components.config_io import save_ui_to_config from gui.components.config_vars import build_config_vars +from gui.components.mousewheel_guard import disable_spinbox_mousewheel from gui.components.run_params_builder import get_params as build_run_params from gui.components.screenshot_action import do_screenshot from gui.components.wifi_adb_dialog import open_wifi_adb_dialog @@ -32,6 +33,7 @@ class DashboardApp: self.root.geometry("1280x860") self.root.minsize(1080, 720) theme.setup_styles(self.root) + disable_spinbox_mousewheel(self.root) self.data = load_dashboard_data() self.runner = Runner(self._on_runner_line) diff --git a/gui/dashboard_app/page_data.py b/gui/dashboard_app/page_data.py index ca4c12c..d4cba29 100644 --- a/gui/dashboard_app/page_data.py +++ b/gui/dashboard_app/page_data.py @@ -84,11 +84,16 @@ def _compact_action_lines(file_lines: list[str], runner_lines: list[str]) -> lis return merged[-700:] -def _scroll_controls(parent: tk.Misc, note: str = "") -> tk.StringVar: +def _scroll_controls(parent: tk.Misc, ctx: PageContext, key: str, note: str = "") -> tuple[tk.StringVar, ttk.Combobox]: controls = tk.Frame(parent, bg=theme.BG) controls.pack(fill="x", pady=(0, 8)) tk.Label(controls, text="滚动:", bg=theme.BG, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left") - scroll_var = tk.StringVar(value="跟随底部") + existing = ctx.vars.get(key) + if isinstance(existing, tk.StringVar): + scroll_var = existing + else: + scroll_var = tk.StringVar(value="跟随底部") + ctx.vars[key] = scroll_var scroll_combo = ttk.Combobox( controls, textvariable=scroll_var, @@ -105,7 +110,7 @@ def _scroll_controls(parent: tk.Misc, note: str = "") -> tk.StringVar: fg=theme.SUBTLE, font=theme.FONT_SMALL, ).pack(side="left", padx=(10, 0)) - return scroll_var + return scroll_var, scroll_combo def _scroll_mode(scroll_var: tk.StringVar) -> str: @@ -137,6 +142,14 @@ def _set_log_text(text: tk.Text, lines: list[str], *, scroll_mode: str = "follow text.yview_moveto(1.0) +def _apply_scroll_strategy(text: tk.Text, scroll_var: tk.StringVar) -> None: + mode = _scroll_mode(scroll_var) + if mode == "top": + text.yview_moveto(0.0) + elif mode == "follow": + text.yview_moveto(1.0) + + def _runner_lines(ctx: PageContext, fallback: list[str]) -> list[str]: runner = ctx.runner if runner is not None: @@ -153,9 +166,10 @@ def _runner_lines(ctx: PageContext, fallback: list[str]) -> list[str]: def build_run_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: section(parent, "运行日志", "实时输出 / 独立滚动 / 刷新") toolbar(parent, [("刷新", ctx.action("refresh"), "soft"), ("行为日志", ctx.action("show_actions_log"), "soft"), "上一个", "下一个", "清除"]) - scroll_var = _scroll_controls(parent) + scroll_var, scroll_combo = _scroll_controls(parent, ctx, "run_log_scroll_mode") box, text = log_panel(parent, "运行日志", _runner_lines(ctx, data.run_log), height=24) box.pack(fill="both", expand=True) + scroll_combo.bind("<>", lambda _e: _apply_scroll_strategy(text, scroll_var), add="+") def refresh_live() -> None: try: @@ -214,10 +228,11 @@ def build_high_value(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> def build_actions_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: section(parent, "行为日志", "actions.log / 独立滚动 / 刷新") toolbar(parent, [("刷新", ctx.action("refresh"), "soft"), ("运行日志", ctx.action("show_run_log"), "soft"), "上一个", "下一个", "清除"]) - scroll_var = _scroll_controls(parent, "合并重复,只看关键操作") + scroll_var, scroll_combo = _scroll_controls(parent, ctx, "actions_log_scroll_mode", "合并重复,只看关键操作") lines = _compact_action_lines(data.action_log, _runner_action_lines(ctx)) box, text = log_panel(parent, "行为日志", lines, height=24) box.pack(fill="both", expand=True) + scroll_combo.bind("<>", lambda _e: _apply_scroll_strategy(text, scroll_var), add="+") def refresh_file() -> None: try: @@ -269,13 +284,29 @@ def build_wins(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: preview_panel(body, data.win_images[0] if data.win_images else None, "截图预览").grid(row=0, column=1, sticky="nsew", padx=(8, 0)) -def _schedule_mapping_refresh(widget: tk.Misc, ctx: PageContext, interval_ms: int = 5000) -> None: +def _mapping_auto_refresh_var(ctx: PageContext) -> tk.BooleanVar: + var = ctx.vars.get("mapping_auto_refresh") + if isinstance(var, tk.BooleanVar): + return var + var = tk.BooleanVar(value=True) + ctx.vars["mapping_auto_refresh"] = var + return var + + +def _schedule_mapping_refresh(widget: tk.Misc, ctx: PageContext, enabled_var: tk.BooleanVar, interval_ms: int = 5000) -> None: + if getattr(widget, "_mapping_refresh_scheduled", False): + return + setattr(widget, "_mapping_refresh_scheduled", True) + def tick() -> None: + setattr(widget, "_mapping_refresh_scheduled", False) try: if not widget.winfo_exists(): return except Exception: return + if not bool(enabled_var.get()): + return refresh = ctx.action("refresh") if refresh: refresh() @@ -289,7 +320,23 @@ def _schedule_mapping_refresh(widget: tk.Misc, ctx: PageContext, interval_ms: in def build_mapping(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: section(parent, "映射表", "显示原始标题 / 刷新映射表 / 搜索 / 复制条目") refresh = ctx.action("refresh") - toolbar(parent, [("自动刷新(5s)", refresh, "soft"), ("刷新映射表", refresh, "soft"), "显示原始标题", "清除", "复制条目"]) + auto_refresh_var = _mapping_auto_refresh_var(ctx) + tools = toolbar(parent, [("刷新映射表", refresh, "soft"), "显示原始标题", "清除", "复制条目"]) + auto_check = tk.Checkbutton( + tools, + text="自动刷新(5s)", + variable=auto_refresh_var, + bg=theme.BG, + fg=theme.TEXT, + activebackground=theme.BG, + activeforeground=theme.TEXT, + selectcolor=theme.SURFACE, + relief="flat", + bd=0, + font=theme.FONT_UI, + cursor="hand2", + ) + auto_check.pack(side="left", padx=(4, 0)) mapping_table = table_panel(parent, "运行时映射表", ( ("pos", "位置", 70), ("title", "标题", 230), ("raw_title", "原始标题", 250), ("reserved", "预约", 64), ("has_fudai", "福袋", 64), ("value", "价值", 90), @@ -297,7 +344,9 @@ def build_mapping(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non ("button", "按钮", 120), ("task", "任务", 180), ("content", "内容", 220), ("updated", "更新时间", 160), ), data.mapping_rows, height=22) mapping_table.pack(fill="both", expand=True) - _schedule_mapping_refresh(mapping_table, ctx) + auto_check.configure(command=lambda: _schedule_mapping_refresh(mapping_table, ctx, auto_refresh_var)) + if bool(auto_refresh_var.get()): + _schedule_mapping_refresh(mapping_table, ctx, auto_refresh_var) def build_wifi_adb(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: diff --git a/gui/dashboard_app/page_home.py b/gui/dashboard_app/page_home.py index b410d71..c70b6ba 100644 --- a/gui/dashboard_app/page_home.py +++ b/gui/dashboard_app/page_home.py @@ -8,10 +8,11 @@ from threading import RLock from typing import Any from . import theme -from .data import DashboardData, fmt_ts +from .data import DashboardData, fmt_ts, load_dashboard_data from .page_context import PageContext from .page_helpers import reservation_rows -from .widgets import flow_grid, log_panel, preview_panel, section, stat_tile, table_panel +from .stats_view import build_stats_dashboard +from .widgets import flow_grid, preview_panel, section, stat_tile, table_panel _RUN_TS_RE = re.compile(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:[.,]\d+)?)") @@ -155,6 +156,9 @@ def _runtime_stats(data: DashboardData, ctx: PageContext) -> dict[str, Any]: try: stats = runner.get_stats() if stats.get("counters") or stats.get("running"): + current_run, total_run = _run_durations(data) + stats.setdefault("dashboard_current_run", current_run) + stats.setdefault("dashboard_total_run", total_run) return stats except Exception: pass @@ -175,12 +179,6 @@ def _counter(stats: dict[str, Any], key: str) -> int: return 0 -def _stats_lines(stats: dict[str, Any]) -> list[str]: - from gui.components.stats_formatter import format_stats - - return format_stats(stats) - - def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: section(parent, "数据看板", "运行时间 / 队列 / 截图") metrics = flow_grid(parent, 3) @@ -215,25 +213,38 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: preview_panel(right, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True) -def build_statistics(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: - section(parent, "统计信息", "旧GUI同源运行统计 / 自动解析运行日志") +def _render_statistics_dashboard(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: + for child in list(parent.winfo_children()): + child.destroy() stats = _runtime_stats(data, ctx) current_run = str(stats.get("dashboard_current_run") or "-") total_run = str(stats.get("dashboard_total_run") or "-") if stats.get("uptime_seconds"): current_run = _fmt_duration(float(stats.get("uptime_seconds") or 0)) - metrics = flow_grid(parent, 4) - values = [ - ("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT), - ("打开详情", _counter(stats, "fudai_open_detail_unique"), "旧GUI口径", theme.BLUE, theme.BLUE_SOFT), - ("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重统计", theme.GREEN, theme.GREEN_SOFT), - ("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT), - ("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT), - ("错误数", _counter(stats, "error_total"), "异常统计", theme.RED, theme.RED_SOFT), - ("本次运行", current_run, "Runner", theme.TEAL, theme.TEAL_SOFT), - ("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT), - ] - for idx, item in enumerate(values): - tile = stat_tile(metrics, *item[:3], color=item[3], soft=item[4], compact=True) - tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4) - log_panel(parent, "运行数据统计", _stats_lines(stats), height=28)[0].pack(fill="both", expand=True) + build_stats_dashboard(parent, stats, current_run, total_run) + + +def _schedule_statistics_refresh(widget: tk.Misc, ctx: PageContext, interval_ms: int = 2000) -> None: + def tick() -> None: + try: + if not widget.winfo_exists(): + return + except Exception: + return + try: + _render_statistics_dashboard(widget, load_dashboard_data(), ctx) + finally: + _schedule_statistics_refresh(widget, ctx, interval_ms) + + try: + widget.after(interval_ms, tick) + except Exception: + pass + + +def build_statistics(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: + section(parent, "统计信息", "实时运行指标 / 旧GUI同源统计") + dashboard = tk.Frame(parent, bg=theme.BG) + dashboard.pack(fill="both", expand=True) + _render_statistics_dashboard(dashboard, data, ctx) + _schedule_statistics_refresh(dashboard, ctx) diff --git a/gui/dashboard_app/stats_view.py b/gui/dashboard_app/stats_view.py new file mode 100644 index 0000000..477408b --- /dev/null +++ b/gui/dashboard_app/stats_view.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import tkinter as tk +from datetime import datetime +from typing import Any + +from . import theme +from .widgets import flow_grid, rounded_surface + + +def _counter(stats: dict[str, Any], key: str) -> int: + counters = stats.get("counters", {}) or {} + try: + return int(counters.get(key, 0) or 0) + except Exception: + return 0 + + +def _fmt_duration(seconds: float) -> str: + seconds = max(0, int(seconds)) + hours, rem = divmod(seconds, 3600) + minutes, secs = divmod(rem, 60) + if hours: + return f"{hours:02d}:{minutes:02d}:{secs:02d}" + return f"{minutes:02d}:{secs:02d}" + + +def _fmt_rate(part: int, total: int) -> str: + if total <= 0: + return "-" + return f"{(part / total) * 100:.1f}%" + + +def _per_hour(value: int, seconds: int | float) -> str: + if value <= 0 or seconds <= 0: + return "-" + return f"{value / (float(seconds) / 3600.0):.1f}/h" + + +def _last_log_time(stats: dict[str, Any]) -> str: + ts = stats.get("last_log_ts") + if not ts: + return "-" + try: + return datetime.fromtimestamp(float(ts)).strftime("%H:%M:%S") + except Exception: + return "-" + + +def _group(parent: tk.Misc, title: str) -> tk.Frame: + box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) + box.pack(fill="both", expand=True) + head = tk.Frame(box, bg=theme.SURFACE) + head.pack(fill="x", padx=16, pady=(14, 8)) + tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10)) + tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left") + body = tk.Frame(box, bg=theme.SURFACE) + body.pack(fill="both", expand=True, padx=16, pady=(0, 14)) + return body + + +def _metric_row(parent: tk.Misc, label: str, value: object, hint: str = "", color: str = theme.TEAL) -> None: + row = tk.Frame(parent, bg=theme.SURFACE) + row.pack(fill="x", pady=4) + tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left") + tk.Label(row, text=str(value), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right") + if hint: + tk.Label(parent, text=hint, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4)) + + +def _kpi_tile(parent: tk.Misc, title: str, value: object, hint: str, color: str, soft: str) -> tk.Frame: + box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) + box.configure(height=104) + box.pack_propagate(False) + accent = tk.Frame(box, bg=color, width=4) + accent.pack(side="left", fill="y") + inner = tk.Frame(box, bg=theme.SURFACE) + inner.pack(side="left", fill="both", expand=True, padx=14, pady=10) + head = tk.Frame(inner, bg=theme.SURFACE) + head.pack(fill="x") + tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left") + tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right") + tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0)) + tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0)) + return box + + +def _bar_row(parent: tk.Misc, label: str, value: int, total: int, color: str = theme.TEAL) -> None: + row = tk.Frame(parent, bg=theme.SURFACE) + row.pack(fill="x", pady=5) + tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left") + tk.Label(row, text=f"{value} {_fmt_rate(value, total)}", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right") + track = tk.Frame(parent, bg=theme.BG_ALT, height=8) + track.pack(fill="x", pady=(0, 4)) + pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total)) + fill = tk.Frame(track, bg=color, height=8) + fill.place(relx=0, rely=0, relwidth=pct, relheight=1) + + +def _build_top_cards(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> None: + uptime = int(stats.get("uptime_seconds") or 0) + if uptime > 0: + current_run = _fmt_duration(uptime) + grid = flow_grid(parent, 4) + values = [ + ("运行状态", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}", theme.TEAL, theme.TEAL_SOFT), + ("本次运行", current_run, "当前轮次", theme.BLUE, theme.BLUE_SOFT), + ("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重口径", theme.GREEN, theme.GREEN_SOFT), + ("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT), + ("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT), + ("打开详情", _counter(stats, "fudai_open_detail_unique"), "详情页", theme.BLUE, theme.BLUE_SOFT), + ("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT), + ("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT), + ] + for idx, item in enumerate(values): + tile = _kpi_tile(grid, *item[:3], color=item[3], soft=item[4]) + tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4) + + +def _build_core_flow(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "核心流程") + seen = _counter(stats, "fudai_seen_unique") + open_detail = _counter(stats, "fudai_open_detail_unique") + click = _counter(stats, "fudai_click_attend_unique") + attend = _counter(stats, "fudai_attend_ok_unique") + win = _counter(stats, "fudai_result_win") + no_win = _counter(stats, "fudai_result_no_win") + _bar_row(body, "识别福袋", seen, max(seen, 1), theme.TEAL) + _bar_row(body, "打开详情", open_detail, max(seen, 1), theme.BLUE) + _bar_row(body, "点击参与", click, max(open_detail, 1), theme.AMBER) + _bar_row(body, "参与成功", attend, max(click, attend, 1), theme.GREEN) + _metric_row(body, "中奖率", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}", theme.RED) + + +def _build_efficiency(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "效率与动作") + uptime = int(stats.get("uptime_seconds") or 0) + _metric_row(body, "识别效率", _per_hour(_counter(stats, "fudai_seen_unique"), uptime), "每小时识别福袋", theme.TEAL) + _metric_row(body, "参与效率", _per_hour(_counter(stats, "fudai_attend_ok_unique"), uptime), "每小时成功参与", theme.GREEN) + _metric_row(body, "切换频率", _per_hour(_counter(stats, "switch_room"), uptime), "每小时切换直播间", theme.AMBER) + ocr_attempt = _counter(stats, "ocr_attempt") + _metric_row(body, "OCR成功率", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}", theme.BLUE) + + +def _build_skip(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "过滤与跳过") + items = [ + ("价值过低", "fudai_skip_value_low", theme.AMBER), + ("人数过少", "fudai_skip_participants_low", theme.BLUE), + ("人数过多", "fudai_skip_participants_high", theme.BLUE), + ("内容过滤", "fudai_skip_content", theme.TEAL), + ("倒计时太短", "fudai_skip_countdown_short", theme.RED), + ("倒计时太长", "fudai_skip_countdown_long", theme.AMBER), + ("需要看播", "fudai_skip_watch_required", theme.RED), + ] + total = sum(_counter(stats, key) for _, key, _ in items) + if total <= 0: + tk.Label(body, text="暂无跳过记录", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8) + return + for label, key, color in items: + value = _counter(stats, key) + if value > 0: + _bar_row(body, label, value, total, color) + + +def _build_reservation(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "预约与回访") + recorded = _counter(stats, "reservation_recorded") + back_success = _counter(stats, "reservation_back_success") + verify_ok = _counter(stats, "reservation_back_verify_ok") + verify_fail = _counter(stats, "reservation_back_verify_fail") + _metric_row(body, "记录预约", recorded, "累计写入预约队列", theme.TEAL) + _metric_row(body, "回退成功", back_success, f"成功率 {_fmt_rate(back_success, recorded)}", theme.GREEN) + _metric_row(body, "回退校验", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}", theme.BLUE) + _metric_row(body, "高价值预约", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高", theme.AMBER) + + +def _build_health(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "运行健康") + total = _counter(stats, "error_total") + detail_errors = _counter(stats, "error_read_detail") + _counter(stats, "fudai_open_error") + vision_errors = _counter(stats, "error_ocr") + _counter(stats, "error_screenshot") + _counter(stats, "error_detection") + _metric_row(body, "总错误数", total, "运行日志异常计数", theme.RED if total else theme.GREEN) + _metric_row(body, "识别/截图异常", vision_errors, "OCR、截图、识别", theme.RED if vision_errors else theme.GREEN) + _metric_row(body, "详情异常", detail_errors, "读详情或打开失败", theme.RED if detail_errors else theme.GREEN) + _metric_row(body, "慢操作", _counter(stats, "slow_operation"), ">5秒操作", theme.AMBER) + + +def _build_latest(parent: tk.Misc, stats: dict[str, Any]) -> None: + body = _group(parent, "最近福袋") + last = stats.get("fudai_last", {}) or {} + if not (last.get("content") or last.get("countdown")): + tk.Label(body, text="暂无最近福袋信息", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8) + return + _metric_row(body, "内容", last.get("content") or "-", color=theme.TEXT) + _metric_row(body, "倒计时", last.get("countdown") or "-", color=theme.BLUE) + _metric_row(body, "价值", f"{last.get('prize_value_yuan') or '-'}", "元", theme.AMBER) + participants = last.get("participants") + copies = last.get("copies") + _metric_row(body, "人数/份数", f"{participants or '-'} / {copies or '-'}", color=theme.TEAL) + + +def build_stats_dashboard(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> tk.Frame: + _build_top_cards(parent, stats, current_run, total_run) + grid = tk.Frame(parent, bg=theme.BG) + grid.pack(fill="both", expand=True) + for col in range(2): + grid.grid_columnconfigure(col, weight=1, uniform="stats") + for row in range(3): + grid.grid_rowconfigure(row, weight=1) + + panels = [ + _build_core_flow, + _build_efficiency, + _build_skip, + _build_reservation, + _build_health, + _build_latest, + ] + for idx, builder in enumerate(panels): + slot = tk.Frame(grid, bg=theme.BG) + slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6) + builder(slot, stats) + return grid