import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.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_marking_pagerdetail_model.dart';
import 'package:marking_app/common/model/report/report_for_marking_pagerdetail_params.dart';
import 'package:marking_app/common/model/report/report_for_subject_teacher_model.dart';
import 'package:marking_app/common/model/report/report_for_subject_teacher_params.dart';
import 'package:marking_app/pages/reports/index.dart';
import 'package:marking_app/routes/RouterManager.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_subject_teacher.g.dart';

class ReportSubjectTeacher extends StatefulWidget {
  final int examId;
  final int classId;
  final int subject;
  final String subjectName;
  ReportSubjectTeacher({required this.examId, required this.classId, required this.subject, required this.subjectName, Key? key}) : super(key: key);

  @override
  State<ReportSubjectTeacher> createState() => _ReportSubjectTeacherState();
}

class _ReportSubjectTeacherState extends State<ReportSubjectTeacher> with CommonMixin {
  OverlayEntry? overlayEntry;
  OverlayState? overlayState;
  bool _showAppBar = true;
  double _scrollOffset = 0.0;
  double _appBarHeight = kToolbarHeight;
  late Future<ReportForSubjectTeacherModel?> _future;

  @override
  void initState() {
    overlayState = Overlay.of(context);
    _future = _getData();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    overlayEntry?.remove();
  }

  @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
            ? null
            : 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(
                  '学科老师报告',
                  size: 16.sp,
                  color: Color.fromRGBO(45, 56, 76, 1),
                ),
                elevation: 0,
                shadowColor: Colors.transparent,
                backgroundColor: Colors.transparent,
              ),
        body: Stack(
          children: [
            // 渐变背景色
            $ScaffoldBgc(),

            MyFutureBuilder.buildFutureBuilderOfSingleInstance<ReportForSubjectTeacherModel>(context, _future, (ReportForSubjectTeacherModel? 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: () => easyThrottle('getSubjectTeacher/\'sReportAgain', () => toUpState(setState, () {}, 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, widget.subjectName, context, (StudentDetailList item) async {
                  int theCurrentIndex = 1;
                  List<String> urls = await getViewOriginalVolume(ReportForMarkingPagerdetailParams(
                    examSubjectSchoolId: item.examSubjectSchoolId,
                    examSubjectId: item.examSubjectId,
                    examInfoId: item.examId,
                    studentExamNum: item.studentExamNum,
                  ));

                  if (urls.isEmpty) {
                    return;
                  }
                  overlayEntry = OverlayEntry(
                    opaque: true,
                    builder: (context1) {
                      return StatefulBuilder(
                        builder: (context2, state) {
                          return Stack(
                            children: [
                              Container(
                                color: Color.fromRGBO(0, 0, 0, 0.7),
                                width: ScreenUtil().screenWidth,
                                height: ScreenUtil().screenHeight,
                              ),
                              CardSwiper(
                                padding: EdgeInsets.zero,
                                cardsCount: urls.length,
                                cardBuilder: (context3, index) {
                                  return Container(
                                    color: Colors.transparent,
                                    alignment: Alignment.center,
                                    child: CachedNetworkImage(
                                      imageUrl: urls[index],
                                      placeholder: (context3, url) => CircularProgressIndicator(),
                                      errorWidget: (context3, url, error) => Icon(Icons.error),
                                    ),
                                  );
                                },
                                onSwipe: (int previousIndex, int? currentIndex, CardSwiperDirection direction) {
                                  state(() => theCurrentIndex = (currentIndex ?? 0) + 1);
                                  return true;
                                },
                              ),
                              Positioned(
                                top: 100.h,
                                right: 22.w,
                                child: InkWell(
                                  onTap: () => overlayEntry?.remove(),
                                  child: Icon(Icons.close, size: 30.sp, color: Colors.white),
                                ),
                              ),
                              Positioned(bottom: 30.h, left: 22.w, child: quickText(theCurrentIndex.toString() + '/' + urls.length.toString(), color: Colors.white, size: 16.sp))
                            ],
                          );
                        },
                      );
                    },
                  );
                  overlayState?.insert(overlayEntry!);
                }),
              );
            })
          ],
        ),
      ),
    );
  }

  /// 获取数据
  Future<ReportForSubjectTeacherModel?> _getData() async {
    try {
      RestClientReport clientReport = await getClientReport();
      BaseStructureResultReport<ReportForSubjectTeacherModel> res = await clientReport.getreportsForSubjectTeacher(ReportForSubjectTeacherParams(
        classId: widget.classId,
        examId: widget.examId,
        subject: widget.subject,
      ));
      if (res.success) {
        return res.data;
      }
      ToastUtils.showError(res.message ?? '请求错误，请重试');
    } catch (e) {
      if (e is CheckedFromJsonException) {
        // JSON 解析失败，处理异常
        toPrint(val: 'JSON 解析失败: ${e.message}');
        toPrint(val: 'JSON 解析失败，出错字段: ${e.key}');
      } else {
        // 其他异常，处理其他错误
        toPrint(val: '发生了其他错误: $e');
      }
    }
    return null;
  }

  // 查看原卷接口
  Future<List<String>> getViewOriginalVolume(ReportForMarkingPagerdetailParams params) async {
    try {
      ToastUtils.showLoading();
      RestClientReport clientReport = await getClientReport();
      BaseStructureResultReport<ReportForMarkingPagerdetailModel> res = await clientReport.getMarkingPagerDetails(params);
      if (res.success && res.data != null) {
        if (res.data!.markingPagerImgs.isEmpty) {
          setTimeOut(1, () => ToastUtils.showInfo('暂时没有数据...'));
        }
        return res.data!.markingPagerImgs;
      }
    } catch (e) {
      toPrint(val: e.toString());
    } finally {
      ToastUtils.dismiss();
    }

    return [];
  }
}

/// 报告body
@swidget
Widget $reportBody(ReportForSubjectTeacherModel datas, String subjectName, BuildContext context, Function(StudentDetailList) call) {
  BaseInfo baseInfo = datas.baseInfo;
  GradeLevel gradeLevel = datas.gradeLevel; // 年级水平
  AllLevel allLevel = datas.allLevel; // 总体水平
  List<StudentRankInfoTopList> improveStudents = datas.studentRankInfoTopList; // 排名上升集合
  List<StudentRankInfoFallList> declineStudents = datas.studentRankInfoFallList; // 排名大幅下降
  List<StudentResultInfoTopList> topFiveStudents = datas.studentResultInfoTopList; // 前5
  List<StudentResultInfoFallList> lastFiveStudents = datas.studentResultInfoFallList; // 后5
  List<QuestionList> questionList = datas.questionList; // 试题分析
  bool questionHasKownledgeName = questionList.any((element) => element.kownledgeName != '');

  List<StudentDetailList> studentDetailList = datas.studentDetailList; // 学生信息

  return Container(
    margin: EdgeInsets.symmetric(horizontal: 16.w),
    child: ScrollConfiguration(
      behavior: EUMNoScrollBehavior(),
      child: ListView(
        // top: 20.h, bottom: 20.h
        children: [
          /// 基本信息
          $baseTitleAndBody(
            title: '基本信息',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $baseicInformationTable(baseInfo),
          ),

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

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

          /// 重点关注学生
          $baseTitleAndBody(
              title: '重点关注学生',
              titleImg: 'assets/images/report_home_icon_burst.png',
              graphicContainer: Column(
                children: [
                  $listTable(
                    titles: [
                      ListTableTitle(title: '大幅进步', titleKey: 'StudentName'),
                      ListTableTitle(title: '排名', titleKey: 'Ranking', alignment: Alignment.center),
                      ListTableTitle(title: '排名提升', titleKey: 'RankChange', alignment: Alignment.center),
                    ],
                    datas: improveStudents.map((e) => e.toJson()),
                  ),
                  SizedBox(height: 10.h),
                  $listTable(
                    titles: [
                      ListTableTitle(title: '大幅下降', titleKey: 'StudentName'),
                      ListTableTitle(title: '排名', titleKey: 'Ranking', alignment: Alignment.center),
                      ListTableTitle(title: '排名下降', titleKey: 'RankChange', alignment: Alignment.center),
                    ],
                    datas: declineStudents.map((e) => e.toJson()),
                  ),
                  SizedBox(height: 10.h),
                  $listTable(
                    titles: [
                      ListTableTitle(title: '班级前5名', titleKey: 'StudentName'),
                      ListTableTitle(title: '成绩', titleKey: 'Result', alignment: Alignment.center),
                      ListTableTitle(title: '', titleKey: '', alignment: Alignment.center),
                    ],
                    datas: topFiveStudents.map((e) => e.toJson()),
                  ),
                  SizedBox(height: 10.h),
                  $listTable(
                    titles: [
                      ListTableTitle(title: '班级后5名', titleKey: 'StudentName'),
                      ListTableTitle(title: '排名', titleKey: 'Result', alignment: Alignment.center),
                      ListTableTitle(title: '', titleKey: '', alignment: Alignment.center),
                    ],
                    datas: lastFiveStudents.map((e) => e.toJson()),
                  )
                ],
              )),

          /// 试题分析
          $baseTitleAndBody(
            title: '试题分析',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $listTableHorizontalScrolling(titles: [
              ListTableTitle(title: '题号', titleKey: 'QuestionNum', widthNum: 60.w),
              ListTableTitle(title: '知识点', titleKey: 'KownledgeName', widthNum: questionHasKownledgeName ? 200.w : 40.w),
              ListTableTitle(title: '正确率', titleKey: 'CorrectRate', alignment: Alignment.center),
              ListTableTitle(
                  title: '正确答案及人数',
                  titleKey: 'StudentName',
                  call: (Map<String, dynamic> info, ListTableTitle titleModel) {
                    List<AnswerDetailModel> correctAnswers = info['CorrectAnswerDetailList'];

                    return Container(
                      child: Column(
                        children: correctAnswers.map((e) {
                          return quickText('${e.option}\/${e.checkCount}');
                        }).toList(),
                      ),
                    );
                  }),
            ], datas: questionList.map((e) => e.toJson())),
          ),

          /// 学生成绩详情
          $baseTitleAndBody(
            title: '学生成绩详情',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: $listTable(
                titles: [
                  ListTableTitle(title: '学生姓名', flex: 2, titleKey: 'StudentName'),
                  ListTableTitle(title: '成绩', alignment: Alignment.center, titleKey: 'Score'),
                  ListTableTitle(title: '班次', alignment: Alignment.center, titleKey: 'Ranking'),
                  ListTableTitle(title: '班次进退步', flex: 2, alignment: Alignment.center, titleKey: 'Step'),
                  ListTableTitle(title: '操作', flex: 2, alignment: Alignment.center, titleKey: ''),
                ],
                datas: studentDetailList.map((e) => e.toJson()),
                operateWidget: (Map<String, dynamic> itemMap) {
                  StudentDetailList item = StudentDetailList.fromJson(itemMap);
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      InkWell(
                        onTap: () {
                          RouterManager.router.navigateTo(
                            context,
                            RouterManager.reportPersonalSubjectPath + '?examId=${item.examId}&userId=${item.userId}&subject=${item.subjectId}&studentName=${Uri.encodeComponent(item.studentName)}&subjectName=${Uri.encodeComponent(subjectName)}',
                            transition: getTransition(),
                          );
                        },
                        child: quickText('报告', size: 12.sp, color: Theme.of(context).primaryColor, decoration: TextDecoration.underline),
                      ),
                      SizedBox(width: 10.w),
                      InkWell(
                        onTap: () => call(item),
                        child: quickText('原卷', size: 12.sp, color: Theme.of(context).primaryColor, decoration: TextDecoration.underline),
                      ),
                    ],
                  );
                }),
          ),
        ],
      ),
    ),
  );
}

/// 基本信息table
@swidget
Widget $baseicInformationTable(BaseInfo baseInfo) {
  List<Map> columns = [
    {'考试名称': baseInfo.examName, '考试类型': baseInfo.examTypeName},
    {'年级': baseInfo.grade, '学科': baseInfo.subjects},
    {'考试日期': baseInfo.examTime, '满分': getDoubleRemoveZero(baseInfo.totalScore) + '分'},
    {'平均分': getDoubleRemoveZero(baseInfo.avgScore) + '分', '最高分': getDoubleRemoveZero(baseInfo.maxScore) + '分'},
    {'优秀率(120)': baseInfo.goodRate, '及格率': baseInfo.passRate},
  ];

  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: 10,
                  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: 6),
                  ),
                ),
                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, required String titleImg, required Widget graphicContainer, EdgeInsetsGeometry? margin}) {
  return Container(
    width: double.infinity,
    margin: 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)),
          ],
        ),
        SizedBox(height: 6.h),
        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: title2 == ''
              ? Container()
              : 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 ListTableTitle {
  int flex;
  final String title;
  final String titleKey;
  final double? minWidthNum;
  final double? widthNum;
  final Alignment? alignment;
  final bool isHtmlContent;
  final Widget Function(Map<String, dynamic>, ListTableTitle)? call;
  ListTableTitle({required this.title, required this.titleKey, this.flex = 1, this.widthNum, this.minWidthNum, this.alignment, this.isHtmlContent = false, this.call});
}

/// table
@swidget
Widget $listTable({required List<ListTableTitle> titles, required Iterable<Map<String, dynamic>> datas, Function? operateWidget}) {
  return Card(
    elevation: 11.h,
    shadowColor: Color.fromRGBO(46, 91, 255, 0.10),
    borderOnForeground: false,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(6).r,
      side: BorderSide(color: Colors.white, width: 1.4.r),
    ),
    child: Padding(
      padding: EdgeInsets.only(bottom: 12.h),
      child: Column(
        children: [
          /// table title
          Container(
            height: 40.h,
            padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 17.w),
            decoration: BoxDecoration(
              color: Color.fromRGBO(240, 243, 255, 1),
              borderRadius: BorderRadius.only(topLeft: Radius.circular(8).r, topRight: Radius.circular(6).r),
            ),
            child: Row(
              children: titles.map((e) {
                return Expanded(
                  flex: e.flex,
                  child: Container(
                    alignment: e.alignment,
                    child: quickText(e.title, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 6),
                  ),
                );
              }).toList(),
            ),
          ),

          /// 数据.
          ...datas.map((e) {
            return Container(
              padding: EdgeInsets.symmetric(vertical: 6.h, horizontal: 17.w),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Color.fromRGBO(240, 243, 255, 1), width: 0.5.r),
              ),
              child: Row(
                children: titles.map(
                  (titleModel) {
                    String val = e[titleModel.titleKey]?.toString() ?? '';
                    var callFun = titleModel.call;

                    return Expanded(
                      flex: titleModel.flex,
                      child: operateWidget != null && titleModel.title == '操作'
                          ? operateWidget(e)
                          : callFun != null
                              ? callFun(e, titleModel)
                              : Container(
                                  alignment: titleModel.alignment,
                                  child: titleModel.isHtmlContent ? HtmlWidget(val) : quickText(val, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 2),
                                ),
                    );
                  },
                ).toList(),
              ),
            );
          }),
        ],
      ),
    ),
  );
}

/// table
@swidget
Widget $listTableHorizontalScrolling({required List<ListTableTitle> titles, required Iterable<Map<String, dynamic>> datas, ScrollController? scrollController, int? fixedIndex, bool showScrollBox = false}) {
  bool theFixed = scrollController != null && fixedIndex != null && fixedIndex > 0;
  List<ListTableTitle> titlesFixed = theFixed ? titles.sublist(0, fixedIndex) : [];

  return Card(
    elevation: 11.h,
    shadowColor: Color.fromRGBO(46, 91, 255, 0.10),
    borderOnForeground: false,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(6).r,
      side: BorderSide(color: Colors.white, width: 1.4.r),
    ),
    child: Container(
        constraints: BoxConstraints(minWidth: double.infinity),
        padding: EdgeInsets.only(bottom: 12.h),
        child: Stack(
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: scrollController,
              child: Column(
                children: [
                  Container(
                    height: 36.h,
                    padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 17.w),
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(240, 243, 255, 1),
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(6).r, topRight: Radius.circular(6).r),
                    ),
                    child: Row(
                        children: titles.map((e) {
                      return Container(
                        width: e.widthNum ?? 100.w,
                        alignment: e.alignment,
                        child: quickText(e.title, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400),
                      );
                    }).toList()),
                  ),

                  /// 数据.
                  ...datas.map((e) {
                    return Container(
                      padding: EdgeInsets.symmetric(vertical: 6.h, horizontal: 17.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: Color.fromRGBO(240, 243, 255, 1), width: 0.5.r),
                      ),
                      child: Row(
                        children: titles.map((titleModel) {
                          String val = e[titleModel.titleKey]?.toString() ?? '';
                          Function? callFun = titleModel.call;
                          Alignment? alignment = titleModel.alignment;
                          MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start;

                          if (alignment != null) {
                            mainAxisAlignment = MainAxisAlignment.center;
                          }

                          return Container(
                            width: titleModel.widthNum ?? titleModel.minWidthNum ?? 100.w,
                            alignment: titleModel.alignment,
                            child: callFun != null
                                ? callFun(e, titleModel)
                                : Row(mainAxisAlignment: mainAxisAlignment, children: [
                                    Expanded(
                                      child: Container(
                                        alignment: titleModel.alignment,
                                        child: quickText(val, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 6),
                                      ),
                                    )
                                  ]),
                          );
                        }).toList(),
                      ),
                    );
                  }),
                ],
              ),
            ),
            if (showScrollBox && theFixed)
              SizedBox(
                width: 86.w * titlesFixed.length,
                child: 
                Column(
                  children: [
                    Container(
                      height: 36.h,
                      padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8.w),
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(240, 243, 255, 1),
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(6).r, topRight: Radius.circular(6).r),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                          children: titlesFixed.map((e) {
                        return Container(
                          alignment: Alignment.center,
                          child: quickText(e.title, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400),
                        );
                      }).toList()),
                    ),

                    /// 数据.
                    ...datas.map((e) {
                      return Container(
                        padding: EdgeInsets.symmetric(vertical: 6.h, horizontal: 17.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Color.fromRGBO(240, 243, 255, 1), width: 0.5.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: titlesFixed.map((titleModel) {
                            String val = e[titleModel.titleKey]?.toString() ?? '';
                            Function? callFun = titleModel.call;
                            Alignment? alignment = titleModel.alignment;
                            MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start;

                            if (alignment != null) {
                              mainAxisAlignment = MainAxisAlignment.center;
                            }

                            return Container(
                              width: 50.w,
                              alignment: Alignment.center,
                              child: callFun != null
                                  ? callFun(e, titleModel)
                                  : Row(mainAxisAlignment: mainAxisAlignment, children: [
                                      Expanded(
                                        child: Container(
                                          alignment: titleModel.alignment,
                                          child: quickText(val, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 6),
                                        ),
                                      )
                                    ]),
                            );
                          }).toList(),
                        ),
                      );
                    }),
                  ],
                ),
              ),
          ],
        )),
  );
}
