import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/date/CalendarController.dart';
import 'package:vbvs_app/controller/sleep/sleep_report_controller.dart';
import 'package:vbvs_app/language/AppLanguage.dart';
import 'package:vbvs_app/pages/common/selectDialog.dart';
import 'package:vbvs_app/pages/sleep_report/component/AIAdviceWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/BreatheCard.dart';
import 'package:vbvs_app/pages/sleep_report/component/BreathePauseNewWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/BreatheStandardWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/CompareSleepWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/DiseasePercentsWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/HeartChangeWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/HeartHealthWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/HeartPointWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/HeartRateCard.dart';
import 'package:vbvs_app/pages/sleep_report/component/HeartRateStandardWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/SkinPercentWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/SleepCard.dart';
import 'package:vbvs_app/pages/sleep_report/component/SleepScoreWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/SleepView.dart';
import 'package:vbvs_app/pages/sleep_report/component/SnoreViewWidget.dart';
import 'package:vbvs_app/pages/sleep_report/component/ZiZhuShenJingPercentWidget.dart';

class MHTNewSleepReportPage extends StatefulWidget {
  var data;
  MHTNewSleepReportPage({super.key, required this.data});

  @override
  State<MHTNewSleepReportPage> createState() => _MHTNewSleepReportPageState();
}

class _MHTNewSleepReportPageState extends State<MHTNewSleepReportPage> {
  SleepReportController sleepReportController = Get.find();
  CalendarController calendarController = Get.find();

  final GlobalKey sleepCardKey = GlobalKey();
  final GlobalKey heartRateCardKey = GlobalKey();
  final GlobalKey breatheCardKey = GlobalKey();
  final ScrollController _scrollController = ScrollController();

  @override
  void didUpdateWidget(MHTNewSleepReportPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.data['name'] != oldWidget.data['name'] ||
        widget.data['itemId'] != oldWidget.data['itemId']) {
      _scrollToTargetComponent(sleepReportController.sleepReport);
    }
  }

  @override
  void initState() {
    sleepReportController.sleepReport.value = {};
    if (widget.data['date'] == null) {
      widget.data['date'] = DateTime.now();
    }
    calendarController.selectedDate.value =
        DateTime.fromMillisecondsSinceEpoch(widget.data['date']);
    sleepReportController.selectedDate.value =
        DateTime.fromMillisecondsSinceEpoch(widget.data['date']);
    if (widget.data['type'] != null) {
      sleepReportController.model.type = widget.data['type'];
    } else {
      sleepReportController.model.type = 1;
    }
    String date = MyUtils.formatToDate(widget.data['date']);
    // String date = '2025-5-27';
    requestWithLog(
        logTitle: "查询睡眠报告",
        method: MyHttpMethod.get,
        queryUrl:
            "https://sleepdata.he-info.com/api/analysis/sleep/analysis?mac=${widget.data['mac']}&time=${date}&type=${sleepReportController.model.type}",
        onSuccess: (res) {
          print(res);
          sleepReportController.sleepReport.value = res.data;
          sleepReportController.updateAll();
          _scrollToTargetComponent(sleepReportController.sleepReport);
        },
        onFailure: (res) {
          TopSlideNotification.show(context,
              text: res.msg!, textColor: themeController.currentColor.sc9);
          sleepReportController.sleepReport.value = {};
          sleepReportController.updateAll();
          print(res);
        });

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    sleepReportController.sleepReport.value = {};
    if (widget.data['date'] == null) {
      widget.data['date'] = DateTime.now();
    }
    calendarController.selectedDate.value =
        DateTime.fromMillisecondsSinceEpoch(widget.data['date']);
    sleepReportController.selectedDate.value =
        DateTime.fromMillisecondsSinceEpoch(widget.data['date']);
    if (widget.data['type'] != null) {
      sleepReportController.model.type = widget.data['type'];
    } else {
      sleepReportController.model.type = 1;
    }
    String date = MyUtils.formatToDate(widget.data['date']);
    // String date = '2025-5-27';
    requestWithLog(
        logTitle: "查询睡眠报告",
        method: MyHttpMethod.get,
        queryUrl:
            "https://sleepdata.he-info.com/api/analysis/sleep/analysis?mac=${widget.data['mac']}&time=${date}&type=${sleepReportController.model.type}",
        onSuccess: (res) {
          print(res);
          sleepReportController.sleepReport.value = res.data;
          sleepReportController.updateAll();
          _scrollToTargetComponent(sleepReportController.sleepReport);
        },
        onFailure: (res) {
          TopSlideNotification.show(context,
              text: res.msg!, textColor: themeController.currentColor.sc9);
          sleepReportController.sleepReport.value = {};
          sleepReportController.updateAll();
          print(res);
        });
    double lineWidth = 115.rpx;
    return LayoutBuilder(
      builder: (context, bodySize) => GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: (widget.data['backgroundImg'] != null &&
                      widget.data['backgroundImg'].toString().isNotEmpty)
                  ? AssetImage(widget.data['backgroundImg'])
                  : AssetImage('assets/img/bgNoImg.png') as ImageProvider,
              fit: BoxFit.fill,
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent, // 背景透明
            appBar: AppBar(
              backgroundColor: widget.data['backgroundColor'] != null
                  ? widget.data['backgroundColor'].withOpacity(0.8)
                  : themeController.currentColor.sc5,
              automaticallyImplyLeading: false,
              iconTheme: IconThemeData(color: themeController.currentColor.sc3),
              titleSpacing: 0,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    /// 居中标题
                    Text(
                      '健康报告'.tr,
                      style: TextStyle(
                        fontFamily: 'Readex Pro',
                        color: themeController.currentColor.sc3,
                        letterSpacing: 0,
                        fontSize: 30.rpx,
                      ),
                    ),

                    /// 左边返回按钮
                    if (widget.data['arrow'] == null ||
                        widget.data['arrow'] == true)
                      Positioned(
                        left: 20,
                        child: returnIconButtomNew,
                      ),
                  ],
                ),
              ),
            ),
            body: SafeArea(
              top: true,
              child: SingleChildScrollView(
                child: Obx(() {
                  var sleepReport = sleepReportController.sleepReport;
                  print(sleepReport);
                  return Column(
                    children: [
                      Padding(
                        padding:
                            EdgeInsetsDirectional.fromSTEB(0, 30.rpx, 0, 0),
                        child: Container(
                          width: double.infinity,
                          constraints: BoxConstraints(
                            minHeight: 90.rpx,
                          ),
                          decoration: BoxDecoration(
                            color: widget.data['backgroundColor'] != null
                                ? widget.data['backgroundColor']
                                : themeController.currentColor.sc5,
                          ),
                          child: Padding(
                            padding: EdgeInsetsDirectional.fromSTEB(
                                30.rpx, 15.rpx, 30.rpx, 15.rpx),
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Stack(
                                  alignment: Alignment.bottomLeft,
                                  children: [
                                    Row(
                                      mainAxisSize: MainAxisSize.max,
                                      children: [
                                        ClickableContainer(
                                          backgroundColor: Colors.transparent,
                                          highlightColor:
                                              themeController.currentColor.sc3,
                                          borderRadius: 8.rpx,
                                          padding: EdgeInsets.all(0),
                                          onTap: () async {
                                            sleepReportController.model.type =
                                                1;
                                            sleepReportController.updateAll();
                                          },
                                          child: Column(
                                            mainAxisSize: MainAxisSize.max,
                                            children: [
                                              Container(
                                                width: 115.rpx, // 固定宽度为 160.rpx
                                                alignment:
                                                    Alignment.center, // 文字居中
                                                child: Text(
                                                  '日报'.tr,
                                                  style: TextStyle(
                                                    fontFamily: 'Inter',
                                                    fontSize: AppConstants()
                                                        .title_text_fontSize,
                                                    letterSpacing: 0.0,
                                                    color: sleepReportController
                                                                .model.type ==
                                                            1
                                                        ? themeController
                                                            .currentColor.sc2
                                                        : themeController
                                                            .currentColor.sc3,
                                                  ),
                                                ),
                                              ),
                                              SizedBox(height: 10.rpx),
                                            ],
                                          ),
                                        ),

                                        // Obx(() {
                                        //   return ClickableContainer(
                                        //     backgroundColor: Colors.transparent,
                                        //     highlightColor:
                                        //         themeController.currentColor.sc3,
                                        //     borderRadius: 8.rpx,
                                        //     padding: EdgeInsets.all(0),
                                        //     onTap: () async {
                                        //       sleepReportController.model.type =
                                        //           2;
                                        //       sleepReportController.updateAll();
                                        //     },
                                        //     child: Column(
                                        //       mainAxisSize: MainAxisSize.max,
                                        //       children: [
                                        //         Container(
                                        //           width: 115.rpx, // 固定宽度为 160.rpx
                                        //           alignment:
                                        //               Alignment.center, // 文字居中
                                        //           child: Text(
                                        //             '周报'.tr,
                                        //             style: FlutterFlowTheme.of(
                                        //                     context)
                                        //                 .bodyMedium
                                        //                 .override(
                                        //                   fontFamily: 'Inter',
                                        //                   fontSize: AppConstants()
                                        //                       .title_text_fontSize,
                                        //                   letterSpacing: 0.0,
                                        //                   color:
                                        //                       sleepReportController
                                        //                                   .model
                                        //                                   .type ==
                                        //                               2
                                        //                           ? themeController
                                        //                               .currentColor
                                        //                               .sc2
                                        //                           : themeController
                                        //                               .currentColor
                                        //                               .sc3,
                                        //                 ),
                                        //           ),
                                        //         ),
                                        //         SizedBox(height: 10.rpx),
                                        //       ],
                                        //     ),
                                        //   );
                                        // }),
                                        // Obx(() {
                                        //   return ClickableContainer(
                                        //     backgroundColor: Colors.transparent,
                                        //     highlightColor:
                                        //         themeController.currentColor.sc3,
                                        //     borderRadius: 8.rpx,
                                        //     padding: EdgeInsets.all(0),
                                        //     onTap: () async {
                                        //       sleepReportController.model.type =
                                        //           3;
                                        //       sleepReportController.updateAll();
                                        //     },
                                        //     child: Column(
                                        //       mainAxisSize: MainAxisSize.max,
                                        //       children: [
                                        //         Container(
                                        //           width: 115.rpx, // 固定宽度为 160.rpx
                                        //           alignment:
                                        //               Alignment.center, // 文字居中
                                        //           child: Text(
                                        //             '月报'.tr,
                                        //             style: FlutterFlowTheme.of(
                                        //                     context)
                                        //                 .bodyMedium
                                        //                 .override(
                                        //                   fontFamily: 'Inter',
                                        //                   fontSize: AppConstants()
                                        //                       .title_text_fontSize,
                                        //                   letterSpacing: 0.0,
                                        //                   color:
                                        //                       sleepReportController
                                        //                                   .model
                                        //                                   .type ==
                                        //                               3
                                        //                           ? themeController
                                        //                               .currentColor
                                        //                               .sc2
                                        //                           : themeController
                                        //                               .currentColor
                                        //                               .sc3,
                                        //                 ),
                                        //           ),
                                        //         ),
                                        //         SizedBox(height: 10.rpx),
                                        //       ],
                                        //     ),
                                        //   );
                                        // }),
                                      ],
                                    ),
                                    AnimatedPositioned(
                                      duration: Duration(milliseconds: 300),
                                      curve: Curves.easeInOut,
                                      bottom: 0,
                                      left: sleepReportController.model.type ==
                                              1
                                          ? 0
                                          : sleepReportController.model.type ==
                                                  2
                                              ? 115.rpx
                                              : 230.rpx,
                                      child: Container(
                                        width: lineWidth,
                                        height: 4.rpx,
                                        decoration: BoxDecoration(
                                          color:
                                              themeController.currentColor.sc2,
                                          borderRadius:
                                              BorderRadius.circular(2.rpx),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                // Padding(
                                //   padding: EdgeInsetsDirectional.fromSTEB(
                                //       0, 0.rpx, 0.rpx, 0),
                                //   child: Container(
                                //     width: 28.rpx,
                                //     height: 28.rpx,
                                //     // width: double.infinity,
                                //     decoration: BoxDecoration(),
                                //     child: SvgPicture.asset(
                                //       'assets/img/icon/share.svg',
                                //       fit: BoxFit.cover,
                                //       color: themeController.currentColor.sc3,
                                //     ),
                                //   ),
                                // ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        child: Padding(
                          padding: EdgeInsetsDirectional.fromSTEB(
                              30.rpx, 32.rpx, 30.rpx, 32.rpx),
                          child: getTimeWidget(),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 58.rpx),
                        child: ClickableContainer(
                          backgroundColor:
                              widget.data['backgroundColor'] != null
                                  ? widget.data['backgroundColor']
                                  : themeController.currentColor.sc5,
                          highlightColor:
                              themeController.currentColor.sc5, // 或你希望的点击水波纹颜色
                          borderRadius: AppConstants()
                              .normal_container_radius, // 如果你想加圆角可以设置 eg. 12.rpx
                          padding: EdgeInsets.zero,
                          onTap: () {},
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Flexible(
                                flex: 2,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Text(
                                              '姓名'.tr,
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc4,
                                              ),
                                            ),
                                            Text(
                                              '年龄'.tr,
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc4,
                                              ),
                                            ),
                                          ].divide(SizedBox(height: 34.rpx)),
                                        ),
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              (widget.data['person']?['name']
                                                          ?.toString()
                                                          .trim()
                                                          .isNotEmpty ??
                                                      false)
                                                  ? widget
                                                      .data['person']!['name']
                                                      .toString()
                                                  : '未知数据'.tr,
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc3,
                                              ),
                                            ),
                                            Text(
                                              '${MyUtils.getAgeByDate(MyUtils.formatBirthdayTime(widget.data['person']?['birthday'])) ?? '未知数据'.tr}',
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc3,
                                              ),
                                            ),
                                          ].divide(SizedBox(height: 34.rpx)),
                                        ),
                                      ]
                                          .divide(SizedBox(width: 33.rpx))
                                          .addToStart(SizedBox(width: 37.rpx)),
                                    ),
                                  ]
                                      .addToStart(SizedBox(height: 36.rpx))
                                      .addToEnd(SizedBox(height: 36.rpx)),
                                ),
                              ),
                              Flexible(
                                flex: 3,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Text(
                                              '设备ID'.tr,
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc4,
                                              ),
                                            ),
                                            Text(
                                              '体重'.tr,
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc4,
                                              ),
                                            ),
                                          ].divide(SizedBox(height: 34.rpx)),
                                        ),
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              '${widget.data['code'] ?? '未知数据'.tr}',
                                              // "D11250300003",
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc3,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            Text(
                                              '${widget.data['person']?['weight'] ?? '未知数据'.tr}kg',
                                              style: TextStyle(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                                color: themeController
                                                    .currentColor.sc3,
                                              ),
                                            ),
                                          ].divide(SizedBox(height: 34.rpx)),
                                        ),
                                      ]
                                          .divide(SizedBox(width: 33.rpx))
                                          .addToStart(SizedBox(width: 37.rpx)),
                                    ),
                                  ]
                                      .addToStart(SizedBox(height: 36.rpx))
                                      .addToEnd(SizedBox(height: 36.rpx)),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              SleepScoreWidget(sleepReport: sleepReport.value),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: SleepViewWidget(
                            sleepReport: sleepReport,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          key: sleepCardKey,
                          width: double.infinity,
                          child: SleepCard(
                            sleepReport: sleepReport,
                            highlightItem: widget.data['itemName'] ?? null,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: CompareSleepWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: HeartPointWidget(
                            sleepReport: sleepReport,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: AIAdviceWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              HeartRateStandardWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          key: heartRateCardKey,
                          width: double.infinity,
                          child: HeartRateCard(
                            sleepReport: sleepReport,
                            highlightItem: widget.data['itemName'] ?? null,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: HeartChangeWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              BreatheStandardWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          key: breatheCardKey,
                          width: double.infinity,
                          child: BreatheCard(
                            sleepReport: sleepReport,
                            highlightItem: widget.data['itemName'] ?? null,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              SnoreViewWidgetWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              BreathePauseNewWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: HeartHealthWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child:
                              DiseasePercentsWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: SkinPercentWidget(sleepReport: sleepReport),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 0.rpx, 30.rpx, 0),
                        child: Container(
                          width: double.infinity,
                          child: ZiZhuShenJingPercentWidget(
                              sleepReport: sleepReport),
                        ),
                      ),
                    ].divide(SizedBox(
                      height: 25.rpx,
                    )),
                  );
                }),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget getTimeWidget() {
    final selectedDate = sleepReportController.selectedDate.value!;
    final type = sleepReportController.model.type;
    bool isChinese = AppLanguage().isChinese();
    String displayText = '';
    if (isChinese) {
      if (type == 1) {
        // 日报
        displayText =
            MyUtils.getFormatChineseTime(selectedDate.millisecondsSinceEpoch);
      } else if (type == 2) {
        // 周报
        final startOfWeek =
            selectedDate.subtract(Duration(days: selectedDate.weekday - 1));
        final endOfWeek = startOfWeek.add(const Duration(days: 6));
        displayText =
            '${MyUtils.getFormatChineseTime(startOfWeek.millisecondsSinceEpoch, showWeekday: false)}-${MyUtils.getFormatChineseTime(endOfWeek.millisecondsSinceEpoch, showWeekday: false)}';
      } else if (type == 3) {
        // 月报
        displayText =
            '${selectedDate.year}年${selectedDate.month.toString().padLeft(2, '0')}月';
      }
    } else {
      if (type == 1) {
        // Daily Report
        displayText =
            MyUtils.getFormatEnglishDate(selectedDate.millisecondsSinceEpoch);
      } else if (type == 2) {
        // Weekly Report
        final startOfWeek =
            selectedDate.subtract(Duration(days: selectedDate.weekday - 1));
        final endOfWeek = startOfWeek.add(const Duration(days: 6));
        displayText =
            '${MyUtils.getFormatEnglishDate(startOfWeek.millisecondsSinceEpoch)} - ${MyUtils.getFormatEnglishDate(endOfWeek.millisecondsSinceEpoch)}';
      } else if (type == 3) {
        // Monthly Report
        displayText =
            '${_getEnglishMonthName(selectedDate.month)} ${selectedDate.year}';
      }
    }

    void onLeftArrowTap() {
      if (type == 1) {
        sleepReportController.selectedDate.value =
            selectedDate.subtract(const Duration(days: 1));
      } else if (type == 2) {
        sleepReportController.selectedDate.value =
            selectedDate.subtract(const Duration(days: 7));
      } else if (type == 3) {
        sleepReportController.selectedDate.value = DateTime(
          selectedDate.year,
          selectedDate.month - 1,
          selectedDate.day,
        );
      }
      calendarController.selectedDate.value =
          sleepReportController.selectedDate.value;
      // String date = MyUtils.formatToDate(widget.data['date']);
      String data = MyUtils.formatDate(calendarController.selectedDate.value!);
      requestWithLog(
          logTitle: "查询睡眠报告",
          method: MyHttpMethod.get,
          queryUrl:
              "https://sleepdata.he-info.com/api/analysis/sleep/analysis?mac=${widget.data['mac']}&time=${data}&type=${sleepReportController.model.type}",
          onSuccess: (res) {
            print(res);
            sleepReportController.sleepReport.value = res.data;
            sleepReportController.updateAll();
          },
          onFailure: (res) {
            TopSlideNotification.show(context,
                text: res.msg!, textColor: themeController.currentColor.sc9);
            sleepReportController.sleepReport.value = {};
            sleepReportController.updateAll();
            print(res);
          });

      sleepReportController.updateAll();
      calendarController.updateAll();
    }

    void onRightArrowTap() {
      if (type == 1) {
        sleepReportController.selectedDate.value =
            selectedDate.add(const Duration(days: 1));
      } else if (type == 2) {
        sleepReportController.selectedDate.value =
            selectedDate.add(const Duration(days: 7));
      } else if (type == 3) {
        sleepReportController.selectedDate.value = DateTime(
          selectedDate.year,
          selectedDate.month + 1,
          selectedDate.day,
        );
      }
      calendarController.selectedDate.value =
          sleepReportController.selectedDate.value;
      String data = MyUtils.formatDate(calendarController.selectedDate.value!);
      requestWithLog(
          logTitle: "查询睡眠报告",
          method: MyHttpMethod.get,
          queryUrl:
              "https://sleepdata.he-info.com/api/analysis/sleep/analysis?mac=${widget.data['mac']}&time=${data}&type=${sleepReportController.model.type}",
          onSuccess: (res) {
            print(res);
            sleepReportController.sleepReport.value = res.data;
            sleepReportController.updateAll();
          },
          onFailure: (res) {
            TopSlideNotification.show(context,
                text: res.msg!, textColor: themeController.currentColor.sc9);
            sleepReportController.sleepReport.value = {};
            sleepReportController.updateAll();
            print(res);
          });
      sleepReportController.updateAll();
      calendarController.updateAll();
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(width: 28.rpx, height: 28.rpx), // 占位
        Row(
          children: [
            ClickableContainer(
              backgroundColor: Colors.transparent,
              highlightColor: themeController.currentColor.sc3,
              padding: EdgeInsets.all(10.rpx),
              borderRadius: 8.rpx,
              onTap: onLeftArrowTap,
              child: SizedBox(
                width: 9.rpx,
                height: 14.rpx,
                child: SvgPicture.asset(
                  'assets/img/icon/arrow_left.svg',
                  color: themeController.currentColor.sc3,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 26.rpx),
              child: Text(
                displayText,
                style: TextStyle(
                  fontSize: AppConstants().normal_text_fontSize,
                  color: themeController.currentColor.sc3,
                ),
              ),
            ),
            ClickableContainer(
              backgroundColor: Colors.transparent,
              highlightColor: themeController.currentColor.sc3,
              padding: EdgeInsets.all(10.rpx),
              borderRadius: 8.rpx,
              onTap: onRightArrowTap,
              child: SizedBox(
                width: 9.rpx,
                height: 14.rpx,
                child: SvgPicture.asset(
                  'assets/img/icon/arrow_right.svg',
                  color: themeController.currentColor.sc3,
                ),
              ),
            ),
          ],
        ),
        ClickableContainer(
          backgroundColor: Colors.transparent,
          highlightColor: themeController.currentColor.sc3,
          padding: EdgeInsets.zero,
          borderRadius: 8,
          onTap: () {
            showSleepCalendarBottomSheet(
              type: sleepReportController.model.type,
              timestamp: selectedDate.millisecondsSinceEpoch,
              context: context,
              onDateSelected: (newDate) {
                sleepReportController.selectedDate.value = newDate;
                calendarController.selectedDate.value = newDate;
                String data =
                    MyUtils.formatDate(calendarController.selectedDate.value!);
                requestWithLog(
                    logTitle: "查询睡眠报告",
                    method: MyHttpMethod.get,
                    queryUrl:
                        "https://sleepdata.he-info.com/api/analysis/sleep/analysis?mac=${widget.data['mac']}&time=${data}&type=${sleepReportController.model.type}",
                    onSuccess: (res) {
                      print(res);
                      sleepReportController.sleepReport.value = res.data;
                      sleepReportController.updateAll();
                    },
                    onFailure: (res) {
                      TopSlideNotification.show(context,
                          text: res.msg!,
                          textColor: themeController.currentColor.sc9);
                      sleepReportController.sleepReport.value = {};
                      sleepReportController.updateAll();
                      print(res);
                    });
                sleepReportController.updateAll();
                calendarController.updateAll();
              },
            );
          },
          child: SizedBox(
            width: 28.rpx,
            height: 28.rpx,
            child: SvgPicture.asset(
              'assets/img/icon/calendar.svg',
              fit: BoxFit.cover,
              color: themeController.currentColor.sc3,
            ),
          ),
        ),
      ],
    );
  }

  static String _getEnglishMonthName(int month) {
    const monthNames = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ];
    return monthNames[month - 1];
  }

  void _scrollToTargetComponent(RxMap sleepReport) {
    if (sleepReport.isEmpty) {
      return;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final targetName = widget.data['name'];
      final targetID = widget.data['itemName'];
      GlobalKey? targetKey;

      List sleepdata = sleepReport['bs'] ?? []; // 睡眠数据
      List heartdata = sleepReport['hrs'] ?? []; // 心率数据
      List breathedata = sleepReport['brs'] ?? []; // 呼吸数据

      if (sleepdata.any((e) => e['id'] == targetID)) {
        targetKey = sleepCardKey;
      } else if (heartdata.any((e) => e['id'] == targetID)) {
        targetKey = heartRateCardKey;
      } else if (breathedata.any((e) => e['id'] == targetID)) {
        targetKey = breatheCardKey;
      } else {
        return;
      }

      if (targetKey?.currentContext != null) {
        Scrollable.ensureVisible(
          targetKey!.currentContext!,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut,
          alignment: 0.1,
        );
      }
    });
  }
}
