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/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/pages/device_bind/componnet/bind_dialog.dart';
import 'package:vbvs_app/pages/sleep_report/chart/TimeSeriesChart.dart';
import 'package:EasyDartModule/EasyDartModule.dart' as es;

class HeartRateStandardWidget extends StatefulWidget {
  var sleepReport;
  HeartRateStandardWidget({super.key, required this.sleepReport});

  @override
  State<HeartRateStandardWidget> createState() =>
      _HeartRateStandardWidgetState();
}

class _HeartRateStandardWidgetState extends State<HeartRateStandardWidget> {
  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
  }

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

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

  @override
  Widget build(BuildContext context) {
    try {
      if (widget.sleepReport == null ||
          widget.sleepReport is! Map ||
          widget.sleepReport.isEmpty) {
        return Container();
      }

      final startTime = widget.sleepReport['startTime'];
      final endTime = widget.sleepReport['endTime'];
      List<Map<String, dynamic>> data =
          (widget.sleepReport['hrbc'] as List).cast<Map<String, dynamic>>();
      final dataPoints = data.map((item) {
        final x = item['st'] as int;
        final y = (item['value'] as num).toDouble(); // 安全地转换为 double
        return TimeSeriesPoint(x, y);
      }).toList();

      List<Map<String, dynamic>> hrs =
          (widget.sleepReport['hrs'] as List).cast<Map<String, dynamic>>();
      //206 平均心率
      //202 基准心率
      //207 最低心率
      //208 最高心率
      // 找 id == 206 的元素（平均心率）
      Map<String, dynamic>? avgHeartRate = hrs.firstWhere(
        (element) => element['id'] == 206,
        orElse: () => {},
      );

// 找 id == 202 的元素（基准心率）
      Map<String, dynamic>? baseHeartRate = hrs.firstWhere(
        (element) => element['id'] == 202,
        orElse: () => {},
      );

// 找 id == 207 的元素（最低心率）
      Map<String, dynamic>? minHeartRate = hrs.firstWhere(
        (element) => element['id'] == 207,
        orElse: () => {},
      );

// 找 id == 208 的元素（最高心率）
      Map<String, dynamic>? maxHeartRate = hrs.firstWhere(
        (element) => element['id'] == 208,
        orElse: () => {},
      );
      String range = baseHeartRate['range'] ?? '';
      int min = 0;
      int max = 0;

      if (range.isNotEmpty && range.contains('~')) {
        List<String> parts = range.split('~');
        if (parts.length == 2) {
          min = int.tryParse(parts[0]) ?? 0;
          max = int.tryParse(parts[1]) ?? 0;
        }
      }
      return Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: themeController.currentColor.sc5,
          borderRadius: BorderRadius.circular(
              AppConstants().normal_container_radius), // 你可以按需调整圆角半径
        ),
        child: Padding(
          padding:
              EdgeInsetsDirectional.fromSTEB(26.rpx, 29.rpx, 26.rpx, 45.rpx),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "心率数据".tr,
                      style: TextStyle(
                          color: themeController.currentColor.sc3,
                          fontSize: AppConstants().title_text_fontSize),
                    ),
                    ClickableContainer(
                      backgroundColor: Colors.transparent,
                      highlightColor: Colors.white, // 或设置为你需要的水波纹颜色
                      padding: EdgeInsetsDirectional.fromSTEB(
                          14.rpx, 0.rpx, 14.rpx, 0), //
                      borderRadius: 0.rpx, // 圆形点击区域
                      onTap: () {
                        showTipDialog(
                          context,
                          Container(
                            child: Text(
                              "心率数据介绍".tr,
                              style: TextStyle(
                                fontSize: 26.rpx,
                                color: themeController.currentColor.sc3,
                              ),
                            ),
                          ),
                        );
                      },
                      child: Container(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            0, 0.rpx, 0.rpx, 0), // 外部 padding 移到内部
                        width: 28.rpx,
                        height: 28.rpx,
                        child: SvgPicture.asset(
                          'assets/img/icon/explain.svg',
                          fit: BoxFit.cover,
                          color: themeController.currentColor.sc4,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 31.rpx,
              ),
              Padding(
                padding:
                    EdgeInsetsDirectional.fromSTEB(0.rpx, 0.rpx, 30.rpx, 0.rpx),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        // 圆形小球容器
                        Container(
                          width: 14.rpx, // 圆球的直径
                          height: 14.rpx,
                          decoration: BoxDecoration(
                            color: themeController.currentColor.sc2, // 小球的颜色
                            shape: BoxShape.circle, // 设置为圆形
                          ),
                        ),
                        SizedBox(width: 15.rpx), // 圆球和文字之间的间隔
                        // 文字
                        Text(
                          '正常范围'.tr + "${range}",
                          style: TextStyle(
                            fontSize:
                                AppConstants().smaller_text_fontSize, // 文字的大小
                            color: themeController.currentColor.sc3, // 文字颜色
                          ),
                        ),
                      ],
                    ),
                    // Container(
                    //   // color: Colors.red,
                    //   width: double.infinity,
                    //   // height: 300.rpx,
                    //   child: TimeSeriesChart(
                    //     startTime: startTime,
                    //     endTime: endTime,
                    //     yMin: min.toDouble(),
                    //     yMax: max.toDouble(),
                    //     dataPoints: dataPoints,
                    //   ),
                    // ),
                    Container(
                      // color: Colors.red,
                      width: double.infinity,
                      // height: 300.rpx,
                      child: TimeSeriesChart(
                        startTime: startTime,
                        endTime: endTime,
                        yMin: 50,
                        yMax: 150,
                        dataPoints: dataPoints,
                        // actYMin: min.toDouble(),
                        // actYMax: max.toDouble(),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsetsDirectional.fromSTEB(
                          30.rpx, 0.rpx, 0.rpx, 0.rpx),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Column(
                            children: [
                              Text(
                                "${avgHeartRate['name']}",
                                style: TextStyle(
                                    color: themeController.currentColor.sc3,
                                    fontSize:
                                        AppConstants().normal_text_fontSize),
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    "${avgHeartRate['value']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc2,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                  ),
                                  Text(
                                    "${avgHeartRate['unit']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc3,
                                        fontSize:
                                            AppConstants().small_text_fontSize),
                                  ),
                                ].divide(SizedBox(
                                  width: 6.rpx,
                                )),
                              ),
                            ],
                          ),
                          Column(
                            children: [
                              Text(
                                "${baseHeartRate['name']}",
                                style: TextStyle(
                                    color: themeController.currentColor.sc3,
                                    fontSize:
                                        AppConstants().normal_text_fontSize),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    "${baseHeartRate['value']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc2,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  Text(
                                    "${baseHeartRate['unit']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc3,
                                        fontSize:
                                            AppConstants().small_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ].divide(SizedBox(
                                  width: 6.rpx,
                                )),
                              ),
                            ],
                          ),
                          Column(
                            children: [
                              Text(
                                "${minHeartRate['name']}",
                                style: TextStyle(
                                    color: themeController.currentColor.sc3,
                                    fontSize:
                                        AppConstants().normal_text_fontSize),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    "${minHeartRate['value']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc2,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  Text(
                                    "${minHeartRate['unit']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc3,
                                        fontSize:
                                            AppConstants().small_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ].divide(SizedBox(
                                  width: 6.rpx,
                                )),
                              ),
                            ],
                          ),
                          Column(
                            children: [
                              Text(
                                "${maxHeartRate['name']}",
                                style: TextStyle(
                                    color: themeController.currentColor.sc3,
                                    fontSize:
                                        AppConstants().normal_text_fontSize),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    "${maxHeartRate['value']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc2,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  Text(
                                    "${maxHeartRate['unit']}",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc3,
                                        fontSize:
                                            AppConstants().small_text_fontSize),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ].divide(SizedBox(
                                  width: 6.rpx,
                                )),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ].divide(SizedBox(
                    height: 18.rpx,
                  )),
                ),
              ),
            ],
          ),
        ),
      );
    } catch (e) {
      es.EasyDartModule.logger.error("打鼾监测绘制异常${e}");
      return Container();
    }
  }
}
