import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:marking_app/common/model/job/job_report_model.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/toast_utils.dart';
import 'package:photo_view/photo_view.dart';

class ReportTable extends StatefulWidget {
  final List headList;
  final List bodyList;
  final int? fixedRows;
  final int? fixedCols;
  final bool? isKG;
  final int jobId;

  const ReportTable({
    Key? key,
    required this.headList,
    required this.bodyList,
    required this.jobId,
    this.fixedCols = 0,
    this.fixedRows = 0,
    this.isKG = false,
  }) : super(key: key);

  @override
  State<ReportTable> createState() => _ReportTableState();
}

class _ReportTableState extends State<ReportTable> {
  final ScrollController _controller = ScrollController();
  int? _sortColumnIndex;
  bool _sortAscending = true;

  void showPeopleListDialog(
      {required BuildContext context,
      required String title,
      required String questionNo,
      required List arr,
      List? dcList}) {
    print(dcList);
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            // insetPadding: EdgeInsets.symmetric(vertical: 20.r,horizontal: 20.r),
            contentPadding: EdgeInsets.all(20.r),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(15.r))),
            content: SizedBox(
              width: MediaQuery.of(context).size.width * 0.7,
              height: MediaQuery.of(context).size.height * 0.7,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Text(
                      title,
                      style: TextStyle(
                          fontSize: 15.sp,
                          color: Color(0xFF3C3C3C),
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                  SizedBox(
                    height: 5.r,
                  ),
                  Row(
                    children: [
                      Text(
                        widget.isKG == true ? '主观题' : '客观题',
                        style: TextStyle(
                            fontSize: 14.sp, color: Color(0xFF436CFF)),
                      ),
                      Text(
                        '―',
                        style: TextStyle(
                            fontSize: 14.sp, color: Color(0xFF436CFF)),
                      ),
                      Text(
                        '第$questionNo题',
                        style: TextStyle(
                            fontSize: 14.sp, color: Color(0xFF436CFF)),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 15.r,
                  ),
                  dcList != null
                      ? Row(
                          children: [
                            Expanded(
                                flex: 1,
                                child: Center(
                                    child: Text(
                                  '未作答人',
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFF6A6A6A)),
                                ))),
                            Expanded(
                                flex: 1,
                                child: Center(
                                    child: Text(
                                  '答对人数',
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFF6A6A6A)),
                                ))),
                            Expanded(
                                flex: 1,
                                child: Center(
                                    child: Text(
                                  '答错人',
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFF6A6A6A)),
                                ))),
                          ],
                        )
                      : Padding(
                          padding: EdgeInsets.only(left: 15.r),
                          child: Text(
                            title,
                            style: TextStyle(
                                fontSize: 12.sp, color: Color(0xFF6A6A6A)),
                          ),
                        ),
                  SizedBox(
                    height: 5.r,
                  ),
                  if (dcList != null)
                    Expanded(
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemBuilder: (context, index) {
                          var item = arr[index];
                          return Container(
                            padding: EdgeInsets.symmetric(vertical: 5.r),
                            color:
                                index.isOdd ? Colors.white : Color(0xFFF0F0F0),
                            child: Row(
                              children: [
                                Expanded(
                                    flex: 1,
                                    child: InkWell(
                                        onTap: () {
                                          goQuickCheckPersonalPath(
                                              item['noAnswerStudents'].id);
                                        },
                                        child: Center(
                                            child: Text(
                                          item['noAnswerStudents'].name,
                                          style: TextStyle(
                                              fontSize: 12.sp,
                                              color: Color(0xFF323232)),
                                        )))),
                                Expanded(
                                    flex: 1,
                                    child: InkWell(
                                        onTap: () {
                                          goQuickCheckPersonalPath(
                                              item['answerOkStudents'].id);
                                        },
                                        child: Center(
                                            child: Text(
                                          item['answerOkStudents'].name,
                                          style: TextStyle(
                                              fontSize: 12.sp,
                                              color: Color(0xFF323232)),
                                        )))),
                                Expanded(
                                    flex: 1,
                                    child: InkWell(
                                        onTap: () {
                                          goQuickCheckPersonalPath(
                                              item['answerNgStudents'].id);
                                        },
                                        child: Center(
                                            child: Text(
                                          item['answerNgStudents'].name,
                                          style: TextStyle(
                                              fontSize: 12.sp,
                                              color: Color(0xFF323232)),
                                        )))),
                              ],
                            ),
                          );
                        },
                        itemCount: arr.length,
                      ),
                    )
                  else
                    arr.length > 0
                        ? Expanded(
                            child: ListView.builder(
                              shrinkWrap: true,
                              itemBuilder: (context, index) {
                                AnswerOkStudents item = arr[index];
                                return InkWell(
                                  onTap: () {
                                    goQuickCheckPersonalPath(item.id);
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                        vertical: 5.r, horizontal: 15.r),
                                    color: index.isOdd
                                        ? Colors.white
                                        : Color(0xFFF0F0F0),
                                    child: Text(
                                      item.name,
                                      style: TextStyle(
                                          fontSize: 12.sp,
                                          color: Color(0xFF323232)),
                                    ),
                                  ),
                                );
                              },
                              itemCount: arr.length,
                            ),
                          )
                        : MyEmptyWidget()
                ],
              ),
            ),
          );
        });
  }

  void goQuickCheckPersonalPath(id) {
    if (id != -1) {
      RouterManager.router.navigateTo(
        context,
        RouterManager.quickCheckPersonalPath +
            '?jobId=${widget.jobId}&studentId=$id',
        transition: getTransition(),
      );
    }
  }

  void zdHandle(BuildContext context, String title, String questionNo,
      List noAnswerStudents, List answerNgStudents, List answerOkStudents) {
    List list = [];
    AnswerOkStudents student = AnswerOkStudents(-1, '-');
    if (noAnswerStudents.length > answerNgStudents.length &&
        noAnswerStudents.length > answerOkStudents.length) {
      for (int i = 0; i < noAnswerStudents.length; i++) {
        var obj = {
          'noAnswerStudents': noAnswerStudents[i],
          'answerNgStudents':
              answerNgStudents.length > i ? answerNgStudents[i] : student,
          'answerOkStudents':
              answerOkStudents.length > i ? answerOkStudents[i] : student
        };
        list.add(obj);
      }
    } else if (answerNgStudents.length > noAnswerStudents.length &&
        answerNgStudents.length > answerOkStudents.length) {
      for (int i = 0; i < answerNgStudents.length; i++) {
        var obj = {
          'noAnswerStudents':
              noAnswerStudents.length > i ? noAnswerStudents[i] : student,
          'answerNgStudents': answerNgStudents[i],
          'answerOkStudents':
              answerOkStudents.length > i ? answerOkStudents[i] : student
        };
        list.add(obj);
      }
    } else if (answerOkStudents.length > noAnswerStudents.length &&
        answerOkStudents.length > answerNgStudents.length) {
      for (int i = 0; i < answerOkStudents.length; i++) {
        var obj = {
          'noAnswerStudents':
              noAnswerStudents.length > i ? noAnswerStudents[i] : student,
          'answerNgStudents':
              answerNgStudents.length > i ? answerNgStudents[i] : student,
          'answerOkStudents': answerOkStudents[i]
        };
        list.add(obj);
      }
    }

    showPeopleListDialog(
        context: context,
        title: title,
        questionNo: questionNo,
        arr: list,
        dcList: []);
  }

  void dcHandle(
      BuildContext context, String title, String questionNo, List arr) {
    showPeopleListDialog(
        context: context, title: title, questionNo: questionNo, arr: arr);
  }

  DataRow _getRow(int index, [Color? color]) {
    assert(index >= 0);
    var item = widget.bodyList[index];
    return DataRow2.byIndex(
      index: index,
      color: color != null ? MaterialStateProperty.all(color) : null,
      cells: [
        DataCell(Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 5.r),
            child: Text(item.questionNo,
                style: TextStyle(fontSize: 12.sp, color: Color(0xFF525252))),
          ),
        )),
        DataCell(Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 5.r),
            child: Text('${item.validRate}%',
                style: TextStyle(fontSize: 12.sp, color: Color(0xFF525252))),
          ),
        )),
        DataCell(InkWell(
          onTap: () {
            zdHandle(context, '作答人数', item.questionNo, item.noAnswerStudents,
                item.answerNgStudents, item.answerOkStudents);
          },
          child: Center(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 5.r),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(item.validCount,
                      style:
                          TextStyle(fontSize: 12.sp, color: Color(0xFF4CC793))),
                  Image.asset(
                    'assets/images/green_right_icon.png',
                    width: 12.r,
                    height: 12.r,
                  ),
                ],
              ),
            ),
          ),
        )),
        DataCell(Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 5.r),
            child: Text('${item.correctRate}%',
                style: TextStyle(fontSize: 12.sp, color: Color(0xFF525252))),
          ),
        )),
        DataCell(Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 5.r),
            child: widget.isKG == true
                ? InkWell(
                    onTap: () {
                      if (item.questionPicture == null)
                        return ToastUtils.showInfo('当前试题没有原题');
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (_) {
                          return Scaffold(
                            appBar: AppBar(),
                            body: PhotoView(
                                imageProvider:
                                    NetworkImage(item.questionPicture!)),
                          );
                        }),
                      );
                    },
                    child: Text('原题',
                        style: TextStyle(
                            fontSize: 12.sp,
                            color: widget.isKG == true
                                ? Color(0xFFFF8A00)
                                : Color(0xFF4CC793))),
                  )
                : Text(item.questionAnswer,
                    style: TextStyle(
                        fontSize: 12.sp,
                        color: widget.isKG == true
                            ? Color(0xFFFF8A00)
                            : Color(0xFF4CC793))),
          ),
        )),
        DataCell(InkWell(
          onTap: () {
            List<String> parts = item.priorityGeneral.split('人');
            dcHandle(context, '${parts[1]}人', item.questionNo,
                item.priorityStudents);
          },
          child: Center(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 5.r),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(item.priorityGeneral,
                      style:
                          TextStyle(fontSize: 12.sp, color: Color(0xFF6888FD))),
                  Image.asset(
                    'assets/images/job_data_right_icon.png',
                    width: 10.r,
                    height: 10.r,
                  )
                ],
              ),
            ),
          ),
        )),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    bool isPadFlag = isPad();
    return DataTable2(
        dividerThickness: 0,
        scrollController: _controller,
        columnSpacing: 0,
        horizontalMargin: 0,
        dataRowHeight: 40.r,
        bottomMargin: 0,
        border: TableBorder(
            horizontalInside: BorderSide(
                width: 1, color: Colors.white, style: BorderStyle.solid),
            bottom: BorderSide(
                width: 1, color: Colors.white, style: BorderStyle.solid),
            verticalInside: BorderSide(
                width: 1, color: Colors.white, style: BorderStyle.solid)),
        headingRowColor: MaterialStateProperty.resolveWith((states) =>
            widget.fixedCols! > 0 ? Colors.white : Colors.transparent),
        /* headingRowDecoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Colors.grey[400]!,
              Colors.grey[200]!,
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),*/
        headingRowDecoration: BoxDecoration(color: Color(0xFFE6E6E6)),
        fixedColumnsColor: Color(0xFFE6E6E6),
        fixedCornerColor: Colors.grey[400],
        minWidth: widget.headList.length > 6
            ? 80.r * widget.headList.length
            : isPadFlag
                ? MediaQuery.of(context).size.width
                : 85.r * widget.headList.length,
        fixedTopRows: widget.fixedRows!,
        fixedLeftColumns: widget.fixedCols!,
        sortColumnIndex: _sortColumnIndex,
        sortAscending: _sortAscending,
        // onSelectAll: (val) => setState(() => selectAll(val)),
        columns: List.generate(widget.headList.length, (index) {
          var item = widget.headList[index];
          return DataColumn2(
            label: Center(
              child: Text(item,
                  style: TextStyle(fontSize: 12.sp, color: Color(0xFF505767))),
            ),
            // size: ColumnSize.S,
            fixedWidth: index == 0
                ? 40.r
                : widget.headList.length > 6
                    ? 80.r
                    : isPadFlag
                        ? (MediaQuery.of(context).size.width - 8.r) /
                            widget.headList.length
                        : 85.r,
          );
        }),
        rows: List<DataRow>.generate(widget.bodyList.length,
            (index) => _getRow(index, Color(0xFFF5F5F5))));
  }
}
