import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_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_student_history_record.dart';
import 'package:marking_app/components/ReturnToHomepage.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/common_utils.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
part 'report_history.g.dart';

class ReportHistory extends StatefulWidget {
  final int userId;
  final int classId;
  final String studentName;

  const ReportHistory({Key? key, required this.classId, required this.userId, required this.studentName}) : super(key: key);

  @override
  State<ReportHistory> createState() => _ReportHistoryState();
}

class _ReportHistoryState extends State<ReportHistory> with CommonMixin, TickerProviderStateMixin {
  bool isWork = true;
  String startDataTime = CommonUtils.getWeekStartDate().toString().substring(0, 10);
  String endDataTime = CommonUtils.getWeekEndDate().toString().substring(0, 10);
  String customTimeStr = '自定义';
  late TabController tabController;
  List<ReportStudentHistoryRecord> dataList = [];
  late final EasyRefreshController refreshController;

  @override
  void initState() {
    print('userId=${widget.userId}&classId=${widget.classId}');
    super.initState();
    refreshController = EasyRefreshController();
    tabController = TabController(length: 3, vsync: this);
    EasyLoading.show(status: 'loading...');
    getList();
  }

  void getList() async {
    if (startDataTime == DateTime.now().toString().substring(0, 10) || DateTime.parse(startDataTime).isAfter(DateTime.now())) {
      DateTime now = DateTime.parse(startDataTime);
      endDataTime = now.add(Duration(days: 1)).toString().substring(0, 10);
      print(now.add(Duration(days: 1)));
    } else {
      endDataTime = DateTime.now().toString().substring(0, 10);
    }
    RestClientReport clientReport = await getClientReport();
    BaseStructureResultReport<List<ReportStudentHistoryRecord>> res =
        // 488491659239519, 488491659190341, '2023-03-08', '2024-04-19'
        await clientReport.getStudentHistroyRecords(widget.userId, widget.classId, startDataTime, endDataTime);
    if (res.success) {
      setState(() {
        dataList = res.data!;
      });
    }

    EasyLoading.dismiss();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFEDF0FF),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          '${widget.studentName}已完成考试报告',
          style: TextStyle(fontSize: 14.r, color: Color(0xFF000000)),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          ReturnToHomepage(),
        ],
      ),
      body: Column(
        children: [
          /* Container(
            width: MediaQuery.of(context).size.width * 0.8,
            height: 40.r,
            margin: EdgeInsets.only(
                top: 10.r, left: MediaQuery.of(context).size.width * 0.2 / 2),
            padding: EdgeInsets.all(2.r),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              children: [
                Expanded(
                    child: InkWell(
                      onTap: (){
                        isWork = true;
                        setState(() {

                        });
                      },
                      child: Container(
                  decoration: BoxDecoration(
                      color: isWork ? Color(0xFF6988FD) : Colors.white,
                      borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Center(
                      child: Text(
                        '作业',
                        style: TextStyle(
                            fontSize: 14.r,
                            color: isWork ? Colors.white : Color(0xFF505E6E)),
                      ),
                  ),
                ),
                    )),
                Expanded(
                    child: InkWell(
                      onTap: (){
                        isWork = false;
                        setState(() {

                        });
                      },
                      child: Container(
                  decoration: BoxDecoration(
                      color: !isWork ? Color(0xFF6988FD) : Colors.white,
                      borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Center(
                      child: Text(
                        '考试',
                        style: TextStyle(
                            fontSize: 14.r,
                            color: !isWork ? Colors.white : Color(0xFF505E6E)),
                      ),
                  ),
                ),
                    )),
              ],
            ),
          ),*/
          SizedBox(
            height: 10.r,
          ),
          JobConditionFilter(
              controller: tabController,
              customTimeStr: customTimeStr,
              customTime: tabController.index != 3 || ((endDataTime == null || endDataTime == '') && (startDataTime == null || startDataTime == ''))
                  ? null
                  : PickerDateRange(
                      startDataTime == null || startDataTime == '' ? null : DateTime.parse(startDataTime!),
                      endDataTime == null || endDataTime == '' ? null : DateTime.parse(endDataTime!),
                    ),
              onTimeFilter: (String? startTime, String? endTime) {
                if (startTime == null && endTime == null) {
                  if (tabController.index == 3) {
                    tabController.animateTo(0);
                  }
                  startDataTime = '';
                  endDataTime = '';
                  customTimeStr = '自定义';
                } else {
                  EasyLoading.show(status: 'loading...');
                  startDataTime = startTime != null ? startTime : '';
                  endDataTime = endTime != null ? endTime : '';
                  setState(() {});
                  getList();
                }

                // _refreshController2.callRefresh();
              },
              refreshTime: (value) {
                if (value != null && value.startDate != null) {
                  customTimeStr = value.startDate?.toString().substring(0, 10) ?? '';
                  setState(() {});
                  if (value.endDate != null) {
                    if (value.startDate!.year == value.endDate!.year) {
                      customTimeStr = value.startDate.toString().substring(5, 10) + '~${value.endDate.toString().substring(5, 10)}';
                      setState(() {});
                    } else {
                      customTimeStr = '$customTimeStr~${value.endDate?.toString().substring(0, 10)}';
                      setState(() {});
                    }
                  }
                }
              }),
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 14.r, horizontal: 14.r),
              child: EasyRefresh(
                firstRefresh: false,
                taskIndependence: true,
                controller: refreshController,
                header: MaterialHeader(),
                footer: TaurusFooter(),
                onRefresh: () async {
                  getList();
                },
                child: dataList.length > 0
                    ? ListView.builder(
                        itemCount: dataList.length,
                        itemBuilder: (context, index) {
                          ReportStudentHistoryRecord item = dataList[index];
                          return InkWell(
                            onTap: () {
                              RouterManager.router
                                  .navigateTo(context, '${RouterManager.completedReportPath}?examId=${item.examId}&studentNo=${item.studentExamNum}');
                            },
                            child: Container(
                              // padding: EdgeInsets.all(6.r),
                              margin: EdgeInsets.only(bottom: 10.r),
                              width: double.infinity,
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: AssetImage('assets/images/report_student_history_bg.png'),
                                  fit: BoxFit.fill,
                                ),
                                border: Border.all(width: 1.r, color: Color.fromRGBO(46, 91, 255, 0.2)),
                                borderRadius: BorderRadius.circular(5.r),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: EdgeInsets.symmetric(
                                      vertical: 10.r,
                                      horizontal: 10.r,
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          item.examName,
                                          style: TextStyle(fontSize: 12.sp, color: Color(0xFF000000)),
                                        ),
                                        Spacer(),
                                        Text(
                                          item.examStartTime,
                                          style: TextStyle(fontSize: 12.sp, color: Color(0xFF4A4A4A)),
                                        )
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 2.r,
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 10.r),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(5.r),
                                    ),
                                    child: item.scoreInfo.length > 0
                                        ? Scrollbar(
                                            // thumbVisibility:true,
                                            child: SingleChildScrollView(
                                              scrollDirection: Axis.horizontal,
                                              child: Row(
                                                children: List.generate(item.scoreInfo.length, (i) {
                                                  ScoreInfo score = item.scoreInfo[i];
                                                  return Row(
                                                    children: [
                                                      Column(
                                                        children: [
                                                          Container(
                                                            height: 22.r,
                                                            width: item.scoreInfo.length > 4
                                                                ? 90.r
                                                                : (MediaQuery.of(context).size.width - 48.r - (item.scoreInfo.length - 1) * 1.5.r) /
                                                                    item.scoreInfo.length,
                                                            decoration: BoxDecoration(
                                                              borderRadius: BorderRadius.only(
                                                                  topLeft: i == 0 ? Radius.circular(4.r) : Radius.zero,
                                                                  topRight: i == item.scoreInfo.length - 1 ? Radius.circular(4.r) : Radius.zero),
                                                              color: Color(0xFFECECEC),
                                                            ),
                                                            child: Center(
                                                              child: Text(
                                                                score.text,
                                                                style: TextStyle(fontSize: 12.sp, color: Color(0xFF8A8A8A)),
                                                              ),
                                                            ),
                                                          ),
                                                          Container(
                                                            height: 30.r,
                                                            width: item.scoreInfo.length > 4
                                                                ? 90.r
                                                                : (MediaQuery.of(context).size.width - 48.r - (item.scoreInfo.length - 1) * 1.5.r) /
                                                                    item.scoreInfo.length,
                                                            decoration: BoxDecoration(
                                                              borderRadius: BorderRadius.only(
                                                                  bottomLeft: i == 0 ? Radius.circular(4.r) : Radius.zero,
                                                                  bottomRight: i == item.scoreInfo.length - 1 ? Radius.circular(4.r) : Radius.zero),
                                                              color: Colors.white,
                                                            ),
                                                            child: Center(
                                                              child: Text(
                                                                score.value.toString(),
                                                                style: TextStyle(fontSize: 12.sp, color: Color(0xFF4A4A4A)),
                                                              ),
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      SizedBox(
                                                        width: i < item.scoreInfo.length - 1 ? 1.5.r : 0.r,
                                                      ),
                                                    ],
                                                  );
                                                }),
                                              ),
                                            ),
                                          )
                                        : Center(
                                            child: Text(
                                            '-暂无数据-',
                                            style: TextStyle(fontSize: 12.sp, color: Color(0xFF8A8A8A)),
                                          )),
                                  ),
                                  SizedBox(
                                    height: 20.r,
                                  ),
                                ],
                              ),
                            ),
                          );
                        })
                    : MyEmptyWidget(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

@hwidget
Widget jobConditionFilter(BuildContext context,
    {required TabController controller,
    PickerDateRange? customTime,
    required Function refreshTime,
    required String customTimeStr,
    required Function(String? startTime, String? endTime) onTimeFilter}) {
  var customTimeState = PickerDateRange(null, null);
  if (customTime != null) {
    customTimeState =
        PickerDateRange(customTime!.startDate != null ? customTime!.startDate : null, customTime!.endDate != null ? customTime!.endDate : null);
  }

  DateTime getMonthStartDate() {
    DateTime now = DateTime.now();
    return DateTime(now.year, now.month, 1); // 获取当前月份的第一天
  }

  DateTime getMonthEndDate() {
    DateTime now = DateTime.now();
    int nextMonth = now.month + 1;
    if (nextMonth > 12) {
      nextMonth = 1;
      now = now.add(Duration(days: 31 - now.day)); // 跨年了，所以加到当前月的最后一天
    } else {
      now = now.add(Duration(days: DateTime(now.year, nextMonth, 0).day - now.day)); // 加到下个月的第一天的前一天，即本月最后一天
    }
    return now;
  }

  return Container(
    decoration: BoxDecoration(
        // color: Color.fromRGBO(244, 244, 244, 1),
        // border: Border(bottom: BorderSide(color: Color.fromRGBO(204, 204, 204, 1), width: 1)),
        ),
    child: Container(
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1.r, color: Color(0xFFCCCCCC)))),
      child: TabBar(
        controller: controller,
        unselectedLabelStyle: TextStyle(fontSize: 12.sp, color: const Color.fromRGBO(102, 102, 102, 1)),
        labelStyle: TextStyle(
          fontSize: 12.sp,
          fontWeight: FontWeight.bold,
          color: Color.fromRGBO(116, 145, 253, 1),
        ),
        isScrollable: true,
        labelColor: Color(0xFF7491FD),
        unselectedLabelColor: Color(0xFF505E6E),
        padding: EdgeInsets.symmetric(horizontal: 14.r),
        // indicatorSize: TabBarIndicatorSize.label, // 设置指示器高度和标签一样高
        onTap: (int val) async {
          switch (val) {
            case 0: // 近一周
              onTimeFilter(
                CommonUtils.getWeekStartDate().toString().substring(0, 10),
                CommonUtils.getWeekEndDate().toString().substring(0, 10),
              );
              break;
            case 1: // 近一个月
              onTimeFilter(
                getMonthStartDate().toString().substring(0, 10),
                getMonthEndDate().toString().substring(0, 10),
              );
              break;
            default: // 自定义
              var dialogData = await showDialog<PickerDateRange?>(
                  context: context,
                  builder: (BuildContext context1) {
                    return Center(
                      child: Container(
                        color: Colors.white,
                        width: isPad() ? ScreenUtil().screenWidth / 2 : ScreenUtil().screenWidth / 1.3,
                        height: ScreenUtil().screenHeight / 2,
                        child: SfDateRangePicker(
                          showActionButtons: true,
                          confirmText: '确定',
                          cancelText: '取消',
                          onSubmit: (p0) {
                            print(p0);
                            Navigator.of(context1).pop(p0);
                            refreshTime(p0);
                          },
                          onCancel: () {
                            Navigator.of(context1).pop();
                          },
                          selectionMode: DateRangePickerSelectionMode.range,
                          initialSelectedRange: customTimeState,
                        ),
                      ),
                    );
                  });
              // startDate: 2024-03-04 18:47:00.117958, endDate: 2024-03-11 18:47:00.117986
              // if (dialogData != null && (dialogData.startDate != null || dialogData.endDate != null)) {}
              onTimeFilter(
                dialogData?.startDate?.toString().substring(0, 10),
                dialogData?.endDate?.toString().substring(0, 10),
              );
              // customTimeState = dialogData!;
              customTimeState = dialogData ?? PickerDateRange(null, null);
          }
        },
        tabs: <Widget>[
          const Tab(text: '近一周'),
          const Tab(text: '近一月'),
          Tab(text: customTimeStr),
        ],
      ),
    ),
  );
}
