import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/annotate_list_to_refresh.dart';
import 'package:making_school_asignment_app/common/job/work_student_params.dart';
import 'package:making_school_asignment_app/common/mixins/event_bus_mixin.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/enum_untils.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/global_widget/MyEmptyWidget.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/page/home_page/children/read_over/widget/task_list_item.dart';
import 'package:making_school_asignment_app/page/home_page/children/student_work_detail/widget/job_condition_filter.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import 'package:making_school_asignment_app/common/job/work_student.dart';

part 'annotate_list.g.dart';

class AnnotateList extends StatefulWidget {
  final int tabIndex;
  final int assessType;

  const AnnotateList(
      {super.key, required this.tabIndex, required this.assessType});

  @override
  State<AnnotateList> createState() => _AnnotateListState();
}

class _AnnotateListState extends State<AnnotateList>
    with RequestToolMixin, SingleTickerProviderStateMixin,EventBusMixin<AnnotateListToRefresh>{
  late RxString customTimeStr = '自定义'.obs;
  int active = 1;
  late RxList<Items> unAnnotateList = RxList();
  late RxList<Items> annotateList = RxList();

  // late int page = 1;

  late TabController tabController2;

  /* 待阅卷 */
  late final EasyRefreshController refreshController1;
  late final EasyRefreshController refreshController2;
  WorkStudentParams params = WorkStudentParams(
    assessType: 0,
    pageSize: 10,
    pageNumber: 1,
  );
  WorkStudentParams params2 = WorkStudentParams(
    assessType: 0,
    pageSize: 10,
    pageNumber: 1,
    startDate: Utils.getWeekStartDate().toString().substring(0, 10),
    endDate: Utils.getWeekEndDate().toString().substring(0, 10),
  );

  @override
  void initState() {
    super.initState();
    params.assessType = widget.assessType;
    params2.assessType = widget.assessType;
    refreshController1 = EasyRefreshController();
    refreshController2 = EasyRefreshController();

    eventOn<AnnotateListToRefresh>(callback: (e){
      refreshController1.callRefresh();
    });
    tabController2 = TabController(length: 4, vsync: this);
    EasyLoading.show(status: 'loading...');
    getUnAnnotateList();
    getAnnotateList();
  }

  @override
  void dispose() {
    refreshController1.dispose();
    refreshController2.dispose();
    tabController2.dispose();
    eventCancel();
    super.dispose();
  }

//待批阅列表
  void getUnAnnotateList() async {
    WorkStudent data = WorkStudent([], 0);
    data = await getClient().getUnAnnotateList(params);
    if (params.pageNumber == 1) {
      unAnnotateList.value = data.items;
    } else {
      List<Items> list = unAnnotateList.value;
      unAnnotateList.value = [...list,...data.items];
    }
    refreshController1.finishRefresh();
    refreshController2.finishRefresh();
    EasyLoading.dismiss();
    // print('state.unAnnotateList.length=${unAnnotateList.length}');
  }

//已批阅列表
  void getAnnotateList() async {
    WorkStudent data = WorkStudent([], 0);
    data = await getClient().getAnnotatedList(params2);
    if (params2.pageNumber == 1) {
      annotateList.value = data.items;
    } else {
      List<Items> list = annotateList.value;
      annotateList.value = [...list,...data.items];
    }

    refreshController1.finishRefresh();
    refreshController2.finishRefresh();
    EasyLoading.dismiss();
    // print('state.annotateList.length=${annotateList.length}');
  }

  /// 刷新方法
  Future<void> onMyRefresh(EasyRefreshController controller, int tab) async {
    /* params.page = RequestConfig.basePage.page;
    List<JobTaskItem> lists = await getData(controller, params, isReFresh: true);
    try {
      tab == 1 ? (markingDatas1 = lists) : (markingDatas2 = lists);
    } catch (e) {}
    toUpState(setState, () {}, mounted);*/
    if (widget.tabIndex == 0) {
      params.pageNumber = 1;
      getUnAnnotateList();
    } else {
      params2.pageNumber = 1;
      getAnnotateList();
    }
  }

  Future<void> getCollect(item) async {
    await getClient().getCollect(item.id);
    if (widget.tabIndex == 0) {
      getUnAnnotateList();
    } else {
      getAnnotateList();
    }
  }

  /// 加载方法
  Future<void> onMyLoad(EasyRefreshController controller, int tab) async {
    /*params.page++;
    List<JobTaskItem> lists = await getData(controller, params);
    if (lists.isNotEmpty) {
      tab == 1 ? markingDatas1.addAll(lists) : markingDatas2.addAll(lists);
      toUpState(setState, () {}, mounted);
    }*/
    if (widget.tabIndex == 0) {
      params.pageNumber++;
      getUnAnnotateList();
    } else {
      params2.pageNumber++;
      getAnnotateList();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (widget.tabIndex == 1)
          Obx(() {
            return JobConditionFilter(
                customTimeStr: customTimeStr.value,
                controller: tabController2,
                hasAll: true,
                jobType: 1,
                customTime: tabController2.index != 2 ||
                        (params2.startDate == null && params2.endDate == null)
                    ? null
                    : PickerDateRange(
                        params2.startDate == null
                            ? null
                            : DateTime.parse(params2.startDate!),
                        params2.endDate == null
                            ? null
                            : DateTime.parse(params2.endDate!),
                      ),
                onTimeFilter: (String? startTime, String? endTime) {
                  if (startTime == null &&
                      endTime == null &&
                      tabController2.index == 2) {
                    tabController2.animateTo(0);
                    params2.endDate =
                        Utils.getWeekEndDate().toString().substring(0, 10);
                    params2.startDate =
                        Utils.getWeekStartDate().toString().substring(0, 10);
                    customTimeStr.value = '自定义';
                  } else {
                    params2.endDate = endTime;
                    params2.startDate = startTime;
                  }
                  params2.pageNumber = 1;
                  EasyLoading.show(status: 'loading...');
                  if (widget.tabIndex == 0) {
                    getUnAnnotateList();
                  } else {
                    getAnnotateList();
                  }
                  // refreshController2.callRefresh();
                },
                refreshTime: (value) {
                  if (value != null && value.startDate != null) {
                    customTimeStr.value =
                        value.startDate?.toString().substring(0, 10) ?? '';

                    if (value.endDate != null) {
                      if (!Utils.isPad() &&
                          value.startDate!.year == value.endDate!.year) {
                        customTimeStr.value =
                            '${value.startDate.toString().substring(5, 10)}~${value.endDate.toString().substring(5, 10)}';
                      } else {
                        customTimeStr.value =
                            '${customTimeStr.value}~${value.endDate?.toString().substring(0, 10)}';
                      }
                    }
                  }
                });
          }),
        Expanded(
            child: IndexedStack(
          index: widget.tabIndex,
          children: <Widget>[
            $EasyRefresh(
                controller: refreshController1,
                tab: 1,
                type: active,
                data: unAnnotateList,
                onLoad: onMyLoad,
                onRefresh: onMyRefresh,
                collectFun: getCollect),
            $EasyRefresh(
                controller: refreshController2,
                tab: 2,
                type: active,
                data: annotateList,
                onLoad: onMyLoad,
                onRefresh: onMyRefresh,
                collectFun: getCollect),
          ],
        )),
      ],
    );
  }
}

/// 已阅卷
/// OnRefreshCallback? onRefresh
///
@swidget
Widget $easyRefresh({
  required EasyRefreshController controller,
  required Future<void> Function(EasyRefreshController controller, int tab)
      onRefresh,
  required Future<void> Function(EasyRefreshController controller, int tab)
      onLoad,
  required List<Items> data,
  required int tab,
  required int type,
  required Future<void> Function(Items item) collectFun,
}) {
  bool completed = tab == 2; // 是否是待批阅
  bool isPadFlag = Utils.isPad();
  return Obx(() {
    return EasyRefresh(
      firstRefresh: false,
      taskIndependence: true,
      /*enableControlFinishLoad: true,
      enableControlFinishRefresh: true,*/
      emptyWidget: data.isEmpty ? const MyEmptyWidget() : null,
      controller: controller,
      header: MaterialHeader(),
      // footer: MaterialFooter(),
      footer: TaurusFooter(),
      child: completed && isPadFlag
          ? GridView(
              padding: EdgeInsets.only(
                  top: 11.h, bottom: 10.h, left: 12.w, right: 12.w),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, //横轴三个子widget
                  mainAxisSpacing: 10.h,
                  crossAxisSpacing: 6.w,
                  childAspectRatio: 1.81 //宽高比为1时，子widget
                  ),
              children: List.generate(data.length, (index) {
                Items item = data[index];
                String subjectName = EnumUtils.formatSubject(item.subject);
                return $reviewedItem(
                    jobTaskItem: item,
                    type: type,
                    subjectName: subjectName,
                    collectFun: collectFun,
                    tabIndex: tab - 1);
              }),
            )
          : ListView.builder(
              padding: EdgeInsets.only(
                  top: 11.h, bottom: 10.h, left: 12.w, right: 12.w),
              itemBuilder: (context, index) {
                Items item = data[index];
                return TaskListItem(
                    completed: completed,
                    jobTaskItem: item,
                    type: type,
                    collectFun: collectFun,
                    tabIndex: tab - 1);
              },
              itemCount: data.length,
            ),
      onRefresh: () => onRefresh(controller, tab),
      onLoad: () => onLoad(controller, tab),
    );
  });
}

@swidget
Widget $reviewedItem({
  required Items jobTaskItem,
  required int type,
  required int tabIndex,
  required String subjectName,
  required Future<void> Function(Items item) collectFun,
}) {
  EdgeInsets padEdg = EdgeInsets.symmetric(horizontal: 10.w);

  return InkWell(
    onTap: () {
      Get.toNamed(Routes.annotateClassPage, arguments: {
        'id': jobTaskItem.id,
        'name': jobTaskItem.name,
        'grade': jobTaskItem.grade,
        'subject': jobTaskItem.subject,
        'completed': true,
        'tabIndex': tabIndex
      });
    },
    child: Container(
      padding: EdgeInsets.only(top: 10.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: Colors.white,
        boxShadow: const [
          BoxShadow(
            color: Color.fromRGBO(210, 216, 241, 1),
            offset: Offset.zero, //阴影y轴偏移量
            blurRadius: 5.8, //阴影模糊程度
            spreadRadius: 0, //阴影扩散程度
          )
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 顶部任务名称
          Padding(
            padding: padEdg,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 32.w,
                  height: 18.h,
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(left: 2.w),
                  decoration: BoxDecoration(
                    color: type == 1
                        ? const Color(0xFF4CC793)
                        : const Color.fromRGBO(255, 175, 56, 1),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(14.r),
                      topRight: Radius.circular(3.r),
                      bottomLeft: Radius.circular(4.r),
                      bottomRight: Radius.circular(4.r),
                    ),
                  ),
                  margin: EdgeInsets.only(top: 3.h, right: 4.w),
                  child: quickText(type == 1 ? '作业' : '考试',
                      color: Colors.white, size: 10.sp),
                ),
                Expanded(
                  child: quickText(jobTaskItem.name,
                      size: 14.sp,
                      color: const Color.fromRGBO(70, 70, 70, 1),
                      maxLines: 2),
                ),
                if (jobTaskItem.isFixed!)
                  Padding(
                    padding: EdgeInsets.only(top: 3.r),
                    child: Text(
                      '已订正',
                      style: TextStyle(
                          fontSize: 10.sp, color: const Color(0xFFF16262)),
                    ),
                  ),
              ],
            ),
          ),

          Padding(
            padding: padEdg,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                quickText(
                  DateTime.parse(jobTaskItem.publishTime)
                      .toString()
                      .substring(0, 10),
                  color: const Color.fromRGBO(97, 97, 97, 1),
                  size: 10.sp,
                  fontWeight: FontWeight.w500,
                ),
                quickText(' / ',
                    color: const Color.fromRGBO(76, 199, 147, 1),
                    size: 10.sp,
                    fontWeight: FontWeight.w500),
                quickText(
                  '参与班级：',
                  color: const Color.fromRGBO(76, 199, 147, 1),
                  size: 9.sp,
                ),
                quickText(
                  '${jobTaskItem.classCount}',
                  color: const Color.fromRGBO(76, 199, 147, 1),
                  size: 10.sp,
                ),
                quickText(' / ',
                    color: const Color.fromRGBO(116, 145, 253, 1),
                    size: 10.sp,
                    fontWeight: FontWeight.w500),
                quickText(
                  '科目：$subjectName',
                  color: const Color.fromRGBO(116, 145, 253, 1),
                  size: 9.sp,
                ),
              ],
            ),
          ),
          /*Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: FavoriteButton(
              jobTaskItem.id,
              jobTaskItem.title,
              margin: EdgeInsets.only(top: 4.h, bottom: 6.h),
            ),
          ),*/
          Container(
            padding: EdgeInsets.symmetric(vertical: 6.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(6.r),
                  bottomRight: Radius.circular(6.r)),
              color: Colors.white,
              boxShadow: const [
                BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, 0.15),
                  offset: Offset(0, -0.0001), //阴影y轴偏移量
                  blurRadius: 4, //阴影模糊程度
                  spreadRadius: 0, //阴影扩散程度
                )
              ],
            ),
            child: Row(children: [
              if (!jobTaskItem.isFixed!)
                Expanded(
                  flex: 1,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (!jobTaskItem.isFixed!) {
                        EasyLoading.show(status: 'loading...');
                        collectFun(jobTaskItem);
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        border: Border(
                            right: BorderSide(
                                width: 1.r, color: const Color(0xFFDCDCDC))),
                      ),
                      child: quickText('收集订正',
                          color: const Color(0xFF4CC793), size: 11.sp),
                    ),
                  ),
                ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Get.toNamed(Routes.jobReportPage, arguments: {
                      'title': jobTaskItem.name,
                      'homeworkId': jobTaskItem.id,
                      'grade': jobTaskItem.grade
                    });
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: quickText('查看报告',
                        color: const Color.fromRGBO(118, 118, 118, 1),
                        size: 11.sp),
                  ),
                ),
              ),
            ]),
          ),
        ],
      ),
    ),
  );
}
