import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:graphic/graphic.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result_report.dart';
import 'package:marking_app/common/model/report/report_for_class_teacher_model.dart';
import 'package:marking_app/common/model/report/report_for_class_teacher_params.dart';
import 'package:marking_app/common/model/report/report_histogram_model.dart';
import 'package:marking_app/common/model/user/user_info_report.dart';
import 'package:marking_app/pages/reports/bar_chart_histogram.dart';
import 'package:marking_app/pages/reports/index.dart';
import 'package:marking_app/pages/reports/report_subject_teacher.dart';
import 'package:marking_app/provider/user_provider.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';

part 'report_class_teacher.g.dart';

class ReportClassTeacher extends StatefulHookConsumerWidget {
  final int examId;
  const ReportClassTeacher({required this.examId, Key? key}) : super(key: key);

  @override
  _ReportSubjectTeacherState createState() => _ReportSubjectTeacherState();
}

class _ReportSubjectTeacherState extends ConsumerState<ReportClassTeacher> with CommonMixin {
  late Positions position;
  bool _showAppBar = true;
  double _scrollOffset = 0.0;
  double _appBarHeight = kToolbarHeight;
  late Future<ReportForClassTeacherModel?> _future; // 
  late ScrollController _scrollController;
  final double fixedScrollDistance = 80.w;
  bool showScrollBox =false;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()..addListener(_scrollListener);
    UserInfoReport _userReport = ref.read(userReportProvider);
    position = _userReport.positions[_userReport.positionIndex];
    _future = _getData();
  }

  void _scrollListener() {
    bool theScrollDistance = _scrollController.offset >= fixedScrollDistance; // 获取当前滚动的距离
    if(theScrollDistance!=showScrollBox){

      toUpState(setState, () =>showScrollBox=theScrollDistance, mounted);
    }
   
  }

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

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.transparent,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        extendBodyBehindAppBar: true,
        appBar: !_showAppBar
            ? AppBar(
                elevation: 0,
                automaticallyImplyLeading: false, // 禁用默认的返回按钮
                shadowColor: Colors.transparent,
                backgroundColor: Colors.transparent,
              )
            : AppBar(
                centerTitle: true, // 标题居中
                leading: IconButton(
                  icon: Icon(Icons.arrow_back_ios, color: Color.fromRGBO(80, 87, 103, 1), size: 20.sp),
                  onPressed: () => Navigator.of(context).pop(),
                ),
                title: quickText(
                  position.grade + (position.className ?? '') + '班主任老师报告',
                  size: 16.sp,
                  color: Color.fromRGBO(45, 56, 76, 1),
                ),
                elevation: 0,
                shadowColor: Colors.transparent,
                backgroundColor: Colors.transparent,
              ),
        body: Stack(
          children: [
            // 渐变背景色
            $ScaffoldBgc(),

            MyFutureBuilder.buildFutureBuilderOfSingleInstance<ReportForClassTeacherModel>(context, _future, (ReportForClassTeacherModel? datas) {
              if (datas == null) {
                return Center(
                  child: Container(
                    child: CupertinoButton(
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      color: Theme.of(context).primaryColor,
                      //按钮被按下时的不透明度程度，0~1之间
                      pressedOpacity: 1,
                      //这也可以自己定义Container然后固定大小进行设置等等
                      child: quickText('没有数据，请重试', color: Colors.white, size: 14.sp),
                      onPressed: () => toUpState(setState, () {
                        _future = _getData();
                      }, mounted),
                    ),
                  ),
                );
              }
              return NotificationListener<ScrollNotification>(
                onNotification: (notification) {
                  if (notification is ScrollUpdateNotification) {
                    bool _oldShowAppBar = _showAppBar;

                    _scrollOffset += notification.scrollDelta!;
                    if (_scrollOffset < 0.0) {
                      _scrollOffset = 0.0;
                    } else if (_scrollOffset > _appBarHeight) {
                      _scrollOffset = _appBarHeight;
                    }
                    if (_scrollOffset == 0.0) {
                      _showAppBar = true;
                    } else if (_scrollOffset == _appBarHeight) {
                      _showAppBar = false;
                    }
                    if (_oldShowAppBar != _showAppBar) setState(() {});
                  }
                  return true;
                },
                child: $reportBody(datas, position, context,scrollController:_scrollController,showScrollBox:showScrollBox),
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 获取数据
  Future<ReportForClassTeacherModel?> _getData() async {
    try {
      RestClientReport clientReport = await getClientReport();
      BaseStructureResultReport<ReportForClassTeacherModel> res = await clientReport.getreportsForClassTeacher(ReportForClassTeacherParams(examId: widget.examId, compareAll: true));
      if (res.success) {
        ReportForClassTeacherModel? model = res.data;
        if (model != null) {
          String schoolGradeName = position.schoolName + position.grade; // 学校年级名称
          model.averageModels = model.avgComparison.avgComparisonList.map((e) {
            return ReportHistogramModel(name: e.name.replaceAll(schoolGradeName, ""), val: e.score);
          }).toList();
        }
        return model;
      }
    } catch (e) {
      if (e is CheckedFromJsonException) {
        // JSON 解析失败，处理异常
        toPrint(val: 'JSON 解析失败: ${e.message}');
        toPrint(val: 'JSON 解析失败，出错字段: ${e.key}');
      } else {
        // 其他异常，处理其他错误
        toPrint(val: '发生了其他错误: $e');
      }
    }
    return null;
  }
}

/// 报告body
@swidget
Widget $reportBody(ReportForClassTeacherModel data, Positions position, BuildContext context,{ScrollController? scrollController,bool showScrollBox=false}) {
  YearLevel yearLevel = data.yearLevel;
  OverallLevel overallLevel = data.overallLevel;
  

  List<ReportHistogramModel> averageModels = data.averageModels;
  List<ExamTagDistributionList> examTagDistributions = data.examTagDistributionList;
  StudentInfo studentInfo = data.studentInfo;
  List<List<String>> studentInfoData = studentInfo.data;
  List<String> studentInfoHeads = studentInfo.heads;
  SubjectRadarMap subjectRadarMap = data.subjectRadarMap;
  List<ExamSubjects> examSubjects = subjectRadarMap.examSubjects;

  List<Map<String, dynamic>> studentInfoIterable = [];
  List<ListTableTitle> titleheads = studentInfoHeads.map((e) => ListTableTitle(title: e, titleKey: e, widthNum: e == '学生姓名' ? 70.w : 60.w)).toList();

  for (var i = 0; i < studentInfoData.length; i++) {
    Map<String, dynamic> theMapData = {};
    List<String> item = studentInfoData[i];
    item.asMap().keys.forEach((elementIndex) {
      dynamic val = item[elementIndex];
      double? newVal = double.tryParse(val);
      theMapData[titleheads[elementIndex].titleKey] = newVal != null ? getDoubleRemoveZero(newVal) : val.toString();
    });
    studentInfoIterable.add(theMapData);
  }
  return Container(
    margin: EdgeInsets.symmetric(horizontal: 16.w),
    child: ScrollConfiguration(
      behavior: EUMNoScrollBehavior(),
      child: ListView(
        children: [
          /// 基本信息
          $baseTitleAndBody(title: '基本信息', titleImg: 'assets/images/report_home_icon_burst.png', graphicContainer: $baseicInformationTable(data.baseInfo)),

          /// 年级水平
          $baseTitleAndBody(
            title: '年级水平',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $levelBoxWidget(title1: '本校参考班级数', title2: '本校排名', val1: yearLevel.actor.toString(), val2: yearLevel.ranking.toString()),
          ),

          /// 总体水平
          $baseTitleAndBody(
            title: '总体水平',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $levelBoxWidget(title1: '总参考班级数', title2: '总排名', val1: overallLevel.actor.toString(), val2: overallLevel.ranking.toString()),
          ),

          /// 单科雷达图
          $baseTitleAndBody(
            title: '单科雷达图',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer:
                // TheRadarChart(radarSubjects: radarSubjects, rawDataSets: rawDataSets),
                TheRadarChart(examSubjects: examSubjects),
          ),

          /// 平均分对比
          $baseTitleAndBody(
            title: '平均分对比',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: Padding(
              padding: EdgeInsets.only(top: 40.h, bottom: 20.h),
              child: Container(
                height: 200.h,
                child: BarChartSample3(averageModels, horizontal: false, aspectRatio: 1.6),
              ),
            ),
          ),

          /// 分段分布
          $baseTitleAndBody(
            title: '分段分布',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $listTable(
              titles: [ListTableTitle(title: '大幅进步', titleKey: 'TagName'), ListTableTitle(title: '人数', titleKey: 'Number')],
              datas: examTagDistributions.map((e) => e.toJson()),
            ),
          ),

          /// 试题分析
          $baseTitleAndBody(
            title: '学生成绩详情',
            subTitle: '（横向滑动查看更多）',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $listTableHorizontalScrolling(titles: titleheads, datas: studentInfoIterable,scrollController:scrollController,showScrollBox:showScrollBox,fixedIndex: 1),
          ),
        ],
      ),
    ),
  );
}

/// 基本信息table
@swidget
Widget $baseicInformationTable(BaseInfo baseInfo) {
  List<Map> columns = [
    {'考试名称': baseInfo.examName, '考试类型': baseInfo.examType},
    {'年级': baseInfo.grade, '学科': baseInfo.subjects.map((e) => e.subjectName).toString()},
    {'考试日期': baseInfo.examTime, '总分值': getDoubleRemoveZero(baseInfo.totalScore)},
    {'平均分': getDoubleRemoveZero(baseInfo.average), '最高分': getDoubleRemoveZero(baseInfo.maxScore)},
    {'优秀率': baseInfo.excellent, '及格率': baseInfo.qualified},
  ];

  return Card(
    elevation: 11.h,
    shadowColor: Color.fromRGBO(46, 91, 255, 0.10),
    borderOnForeground: true,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(6).r,
      side: BorderSide(color: Colors.white, width: 1.4.r),
    ),
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 14.h),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Color.fromRGBO(232, 235, 255, 1), width: 1.3.r),
          borderRadius: BorderRadius.circular(4).r,
        ),
        child: Column(mainAxisSize: MainAxisSize.min, children: columns.map((e) => $getTableRow(e)).toList()),
      ),
    ),
  );
}

@swidget
Widget $getTableRow(Map datas) {
  return IntrinsicHeight(
    child: Container(
      decoration: BoxDecoration(border: Border.all(color: Color.fromRGBO(229, 234, 255, 1), width: 0.4.r)),
      child: Row(
        children: datas.entries.map((entry) {
          return Expanded(
            child: Row(
              children: [
                Expanded(
                  flex: 9,
                  child: Container(
                    height: double.infinity,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.all(9.5).r,
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(245, 247, 255, 1),
                    ),
                    child: quickText(entry.key, color: Color.fromRGBO(80, 87, 103, 1), size: 12.sp, fontWeight: FontWeight.w400, maxLines: 2),
                  ),
                ),
                Expanded(
                  flex: 11,
                  child: Container(
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.all(9.5).r,
                    child: quickText(entry.value, color: Color.fromRGBO(45, 56, 76, 1), size: 12.sp, fontWeight: FontWeight.w500, maxLines: 6),
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    ),
  );
}

/// 基本信息table
@swidget
Widget $baseTitleAndBody({required String title, String? subTitle, required String titleImg, required Widget graphicContainer}) {
  return Container(
    width: double.infinity,
    margin: EdgeInsets.only(bottom: 28.h),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [Image.asset(titleImg, width: 22.w, height: 22.h), SizedBox(width: 2.w), quickText(title, size: 16.sp, color: Color.fromRGBO(45, 56, 76, 1)), if (subTitle != null) quickText(subTitle, size: 12.sp, color: Color.fromRGBO(45, 56, 76, 1))],
        ),
        SizedBox(height: 6.h),
        Card(
          elevation: 11.h,
          shadowColor: Color.fromRGBO(46, 91, 255, 0.10),
          borderOnForeground: true,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(6).r,
            side: BorderSide(color: Colors.white, width: 1.4.r),
          ),
          child: graphicContainer,
        ),
      ],
    ),
  );
}

// 年级水平Widget
@swidget
Widget $levelBoxWidget({required String title1, required String title2, required String val1, required String val2}) {
  return Container(
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Container(
            padding: EdgeInsets.only(left: 19.w, top: 16.h, bottom: 16.h),
            decoration: BoxDecoration(
              image: const DecorationImage(image: AssetImage('assets/images/report_level_bgm.png'), fit: BoxFit.fill),
              borderRadius: BorderRadius.circular(6).r,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                quickText(title1, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 2),
                SizedBox(height: 8.h),
                quickText(val1, size: 16.sp, color: Color.fromRGBO(45, 56, 76, 1), fontWeight: FontWeight.w700),
              ],
            ),
          ),
        ),
        SizedBox(width: 22.w),
        Expanded(
          child: Container(
            padding: EdgeInsets.only(left: 19.w, top: 16.h, bottom: 16.h),
            decoration: BoxDecoration(
              image: const DecorationImage(image: AssetImage('assets/images/report_level_bgm.png'), fit: BoxFit.fill),
              borderRadius: BorderRadius.circular(6).r,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                quickText(title2, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 2),
                SizedBox(height: 8.h),
                quickText(val2, size: 16.sp, color: Color.fromRGBO(45, 56, 76, 1), fontWeight: FontWeight.w700),
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

class TheRadarChart extends StatelessWidget {
  // final List<RawTitle> radarSubjects;
  // final List<RawDataSet> rawDataSets;
  // const TheRadarChart({required this.radarSubjects, required this.rawDataSets, Key? key}) : super(key: key);
  final List<ExamSubjects> examSubjects;
  const TheRadarChart({required this.examSubjects, Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const adjustData = [
      {"type": "Email", "index": 'dafa0', "value": 120},
      {"type": "Email", "index": 'dafa1', "value": 132},
      {"type": "Email", "index": 'dafa2', "value": 101},
      {"type": "Email", "index": 'dafa3', "value": 134},
      {"type": "Email", "index": 'dafa4', "value": 90},
      {"type": "Email", "index": 'dafa5', "value": 230},
      {"type": "Email", "index": 'dafa6', "value": 210},
    ];

    // @JsonKey(name: 'Subject')
    // String subject;

    // @JsonKey(name: 'Score')
    // double score;

    // @JsonKey(name: 'TotalScore')
    // double totalScore;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30.w),
      child: Chart(
        data: examSubjects.map((e) => e.toJson()).toList(),
        variables: {
          'Subject': Variable(
            accessor: (Map map) => map['Subject'].toString(), // +'('+map['TotalScore'].toString()+')'
          ),
          'Score': Variable(
            accessor: (Map map) => map['Score'] as num,
          ),
        },
        marks: [
          LineMark(
            position: Varset('Subject') * Varset('Score'),
            label: LabelEncode(encoder: (Map<String, dynamic> map) => Label(doubleToStringAsFixed(map['Score']))),
            shape: ShapeEncode(value: BasicLineShape(loop: true)),
            color: ColorEncode(variable: 'Subject', values: Defaults.colors10),
          )
        ],
        coord: PolarCoord(),
        axes: [
          Defaults.circularAxis,
          Defaults.radialAxis,
        ],
        selections: {},
        tooltip: TooltipGuide(
          anchor: (_) => Offset.zero,
          align: Alignment.bottomRight,
          multiTuples: true,
          variables: ['Subject', 'Score'],
        ),
        crosshair: CrosshairGuide(followPointer: [false, true]),
      ),
      // Chart(
      //   data: adjustData,
      //   variables: {
      //     'index': Variable(
      //       accessor: (Map map) => map['index'].toString(),
      //     ),
      //     'type': Variable(
      //       accessor: (Map map) => map['type'] as String,
      //     ),
      //     'value': Variable(
      //       accessor: (Map map) => map['value'] as num,
      //     ),
      //   },
      //   marks: [
      //     LineMark(
      //       position: Varset('index') * Varset('value'),
      //       shape: ShapeEncode(value: BasicLineShape(loop: true)),
      //       color: ColorEncode(variable: 'type', values: Defaults.colors10),
      //     )
      //   ],
      //   coord: PolarCoord(),
      //   axes: [
      //     Defaults.circularAxis,
      //     Defaults.radialAxis,
      //   ],
      //   selections: {
      //     // 'touchMove': PointSelection(
      //     //   on: {GestureType.scaleUpdate, GestureType.tapDown, GestureType.longPressMoveUpdate},
      //     //   dim: Dim.x,
      //     //   variable: 'index',
      //     // )
      //   },
      //   tooltip: TooltipGuide(
      //     anchor: (_) => Offset.zero,
      //     align: Alignment.bottomRight,
      //     multiTuples: true,
      //     variables: ['type', 'value'],
      //   ),
      //   crosshair: CrosshairGuide(followPointer: [false, true]),
      // ),

      // Echarts(
      //   option: '''
      //           {
      //             radar: {
      //               shape: 'circle',
      //               indicator: ${radarSubjects.map((e) => jsonEncode(e.toJson())).toList()}
      //             },
      //             series: [
      //               {
      //                 name: 'Budget vs spending',
      //                 type: 'radar',
      //                 itemStyle: {
      //                     color: '#2E5BFF', // 设置每个点的颜色
      //                 },
      //                 lineStyle: {
      //                     color: '#2E5BFF', // 设置线条的颜色
      //                 },
      //                 data: ${rawDataSets.map((e) => jsonEncode(e)).toList()},
      //                 label: {
      //                   show: true,
      //                   formatter: function(params) {
      //                     return params.value; // 设置标签显示的内容为每个点的值
      //                   },
      //                 },
      //               }
      //             ]
      //           }
      //             ''',
      // ),
      height: 460.h,
    );
  }
}
