import 'package:flutter/foundation.dart';
import 'package:flutter/material.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/marking_models/do_paper_details_param.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/configuration_files/index.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';

import 'original_manuscript_handwriting/answer_handwriting_view.dart';

part 'dropdown_switch_students_type.g.dart';

/// 学生和页码切换
class DropdownSwitchStudentsType extends StatefulWidget {
  const DropdownSwitchStudentsType({super.key});

  @override
  State<DropdownSwitchStudentsType> createState() => _DropdownSwitchStudentsTypeState();
}

class _DropdownSwitchStudentsTypeState extends State<DropdownSwitchStudentsType> {
  final logic = Get.find<HomeworkReviewLogic>();
  final sateData = Get.find<HomeworkReviewLogic>().state.data;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 2.r, left: 12.r, right: 12.r),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: const Color.fromRGBO(46, 91, 255, 0.2),
            offset: Offset(2.w, 2.h), //阴影y轴偏移量
            blurRadius: 14, //阴影模糊程度
            spreadRadius: 0.5, //阴影扩散程度
          )
        ],
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Container(
              padding: EdgeInsets.only(left: 10.w),
              decoration: BoxDecoration(
                color: const Color.fromRGBO(244, 244, 244, 1),
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Obx(() {
                return DropdownButton(
                  isExpanded: true,
                  underline: Container(),
                  padding: EdgeInsets.only(right: 4.w),
                  icon: const Icon(Icons.keyboard_arrow_down_rounded),
                  value: sateData.value?.templateId,
                  hint: const Text('请选择作业页码'), // 锚点的显示文本
                  items: sateData.value?.templateIdKeys?.map((e) {
                    return DropdownMenuItem(
                      value: e,
                      child: quickText('${sateData.value!.templateIdKeyMap![e]}页', color: const Color.fromRGBO(79, 79, 79, 1), size: 14.sp),
                    );
                  }).toList(),
                  onChanged: (value) {
                    if (logic.state.param.value.templateId == value) return;
                    logic.state.param.value.templateId = value;
                    logic.state.param.value = DoPaperDetailsParam.fromJson(logic.state.param.value.toJson());
                    // _useSwitchStudentAndType.currentTab.value = _useSwitchStudentAndType.tabs.value.firstWhere((element) => element.pageIndex == value);
                  },
                );
              }),
            ),
          ),
          const Expanded(flex: 1, child: SizedBox()),
          Expanded(
            flex: 3,
            child: Stack(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 13.w),
                  decoration: BoxDecoration(
                    color: const Color.fromRGBO(244, 244, 244, 1),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Obx(() {
                    return DropdownButton(
                      padding: EdgeInsets.only(right: 4.w),
                      icon: const Icon(Icons.keyboard_arrow_down_rounded),
                      value: sateData.value?.studentId,
                      underline: Container(),
                      isExpanded: true,
                      items: sateData.value?.students.map((e) {
                        return DropdownMenuItem(
                          value: e.id,
                          child: Stack(
                            alignment: const FractionalOffset(0, 0.62),
                            children: [
                              Container(
                                padding: sateData.value?.studentId != e.id && e.isPriority ? EdgeInsets.only(left: 14.w) : null,
                                child: quickText(
                                  e.name,
                                  size: 14.sp,
                                  color: const Color.fromRGBO(79, 79, 79, 1),
                                ),
                              ),
                              if (e.isPriority && sateData.value?.studentId != e.id)
                                Stack(
                                  alignment: const FractionalOffset(0.52, 0.24),
                                  children: [
                                    Icon(
                                      const IconData(0xe63d, fontFamily: "AlibabaIcon"),
                                      size: 12.sp,
                                      color: e.isPriority ? const Color.fromRGBO(76, 199, 147, 1) : const Color.fromRGBO(164, 164, 164, 1),
                                    ),
                                    quickText('优先', size: 4.sp, color: Colors.white),
                                  ],
                                ),
                            ],
                          ),
                        );
                      }).toList(),
                      hint: const Text('请选择学生'), // 锚点的显示文本
                      onChanged: (value) {
                        if (logic.state.param.value.studentId == value) return;
                        logic.state.param.value.studentId = value;
                        logic.state.param.value = DoPaperDetailsParam.fromJson(logic.state.param.value.toJson());
                      },
                    );
                  }),
                ),
                Positioned(
                  left: 2.w,
                  child: Stack(
                    alignment: const FractionalOffset(0.52, 0.24),
                    children: [
                      Obx(() {
                        return Icon(
                          const IconData(0xe63d, fontFamily: "AlibabaIcon"),
                          size: 12.sp,
                          color: sateData.value?.priority ?? false ? const Color.fromRGBO(76, 199, 147, 1) : const Color.fromRGBO(164, 164, 164, 1),
                        );
                      }),
                      quickText('优先', size: 4.sp, color: Colors.white),
                    ],
                  ),
                ),
              ],
            ),
          ),
          // const Expanded(flex: 1, child: SizedBox()),
          SizedBox(width: 8.w),
          Expanded(
            flex: isPad() ? 4 : 5,
            child: const Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                $ContinueToReview(), // 继续批阅
                $HistoryHomework(), // 学生历史作业
                $StudentHandwriting(), // 学生笔迹
              ],
            ),
          ),
        ],
      ),
    );
  }
}

@swidget
Widget $studentHandwriting(BuildContext context) {
  final logic = Get.find<HomeworkReviewLogic>();
  final sateData = Get.find<HomeworkReviewLogic>().state.data;
  return InkWell(
      onTap: () => easyThrottle(
            'SHOW_ANSWER_HANDWRITING',
            () async {
              var homeworkId = logic.state.param.value.homeworkId;
              var studentId = sateData.value?.studentId;
              if (studentId == null) return;
              var templateIdKeyMap = sateData.value?.templateIdKeyMap;
              int? pageNum;
              var templateId = sateData.value?.templateId;
              if (templateIdKeyMap != null && templateId != null) {
                pageNum = templateIdKeyMap[templateId];
              }
              await showAnswerHandwriting(context, homeworkId: homeworkId, studentId: studentId, templateId: templateId, pageNum: pageNum);
              ToastUtils.dismiss();
            },
          ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.edit_outlined, size: 12.sp, color: Theme.of(context).primaryColor.withOpacity(0.8)),
          SizedBox(width: 1.w),
          quickText(
            '学生笔迹',
            size: 12.sp,
            decoration: TextDecoration.underline,
            color: Theme.of(context).primaryColor.withOpacity(0.9),
          ),
        ],
      ));
}

@swidget
Widget $continueToReview(BuildContext context, {bool isFloatingAction = false}) {
  final logic = Get.find<HomeworkReviewLogic>();
  final sateData = Get.find<HomeworkReviewLogic>().state.data;
  return Obx(() {
    var data = sateData.value;
    var param = logic.state.param.value;
    int? submitCount = data?.submitCount; // 提交数量
    int? annotatedCount = data?.annotatedCount; // 批阅数量

    if (data == null || (submitCount == annotatedCount || (param.templateId == null && param.studentId == null))) return const SizedBox();
    callFun() => easyThrottle(
          'DO_PAPERS_JOB_CONTINUE_TO_REVIEW',
          () {
            var param = logic.state.param.value;
            param.templateId = null;
            param.studentId = null;
            logic.state.param.value = DoPaperDetailsParam.fromJson(param.toJson());
          },
        );
    if (isFloatingAction) {
      return FloatingActionButton(
        elevation: 8,
        tooltip: "继续批阅",
        backgroundColor: Colors.white,
        onPressed: callFun,
        child: Icon(Icons.flip_camera_android_outlined, size: 20.sp, color: Theme.of(context).primaryColor),
      );
    }
    return SizedBox(
        child: InkWell(
      onTap: callFun,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.flip_camera_android_outlined, size: 12.sp, color: Theme.of(context).primaryColor.withOpacity(0.8)),
          SizedBox(width: 1.w),
          quickText(
            '继续批阅',
            size: 12.sp,
            decoration: TextDecoration.underline,
            color: Theme.of(context).primaryColor.withOpacity(0.9),
          ),
          SizedBox(width: 2.w),
        ],
      ),
    ));
  });
}

// 学生历史作业
@swidget
Widget $historyHomework(BuildContext context) {
  final sateData = Get.find<HomeworkReviewLogic>().state.data;
  return SizedBox(
    child: InkWell(
      onTap: () => easyThrottle('DO_PAPERS_JOB_HISTORICAL_HOMEWORK', () {
        int? studentId = sateData.value?.studentId;
        if (kDebugMode) print(studentId);
        if (studentId == null || (sateData.value?.students.isEmpty ?? true)) return;
        var currentStudent = sateData.value!.students.firstWhereOrNull((e) => e.id == studentId);
        if (currentStudent == null) return;
        Get.toNamed(Routes.studentWorkDetailPage, arguments: {'studentId': studentId, 'studentName': currentStudent.name});
      }),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.location_history, size: 12.sp, color: const Color.fromRGBO(104, 103, 103, 1)),
          SizedBox(width: 1.w),
          quickText(
            '历史作业',
            size: 12.sp,
            decoration: TextDecoration.underline,
            color: Theme.of(context).primaryColor.withOpacity(0.8),
          ),
        ],
      ),
    ),
  );
}
