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:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/job/job_concerned_with_student.dart';
import 'package:marking_app/common/model/job/job_concerned_with_student_params.dart';
import 'package:marking_app/common/model/job/job_task_item.dart';
import 'package:marking_app/components/ReturnToHomepage.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/request/rest_client.dart';

class AnswerTrajectoryJobDetail extends StatefulWidget {
  final int jobId;
  final String jobName;
  final String genderName;

  const AnswerTrajectoryJobDetail(
      {Key? key,
      required this.jobId,
      required this.jobName,
      required this.genderName})
      : super(key: key);

  @override
  State<AnswerTrajectoryJobDetail> createState() =>
      _AnswerTrajectoryJobDetailState();
}

class _AnswerTrajectoryJobDetailState extends State<AnswerTrajectoryJobDetail>
    with CommonMixin {
  List<MarkingTasks> markList = [];
  late MarkingTasks currentClass;
  List<JobConcernedWithStudent> students = [];
  late final EasyRefreshController refreshController;

  @override
  void initState() {
    super.initState();
    refreshController = EasyRefreshController();
    EasyLoading.show(status: 'loading...');
    getData();
  }

  void getData() async {
    RestClient _client = await getClient();
    BaseStructureResult<List<MarkingTasks>> res =
        await _client.getJobListParticipateInClass(widget.jobId);
    if (res.success) {
      setState(() {
        markList = res.data!;
        if (markList.length > 0) {
          currentClass = markList[0];
          getStudentList();
        }
      });
    }
  }

  void getStudentList() async {
    RestClient _client = await getClient();
    BaseStructureResult<List<JobConcernedWithStudent>> res =
        await _client.getJobWithStudents(JobConcernedWithStudentParams([currentClass.id]));
    if (res.success) {
      setState(() {
        students = res.data!;
      });
    }
    refreshController.finishRefresh();
    EasyLoading.dismiss();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF5F5F5),
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text(
          widget.jobName,
          style: TextStyle(fontSize: 14.sp, color: Color(0xFF333333)),
          overflow: TextOverflow.ellipsis,
        ),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          ReturnToHomepage(),
        ],
      ),
      body: Column(
        children: [
          SizedBox(
            height: 10.r,
          ),
          if (markList.length > 0)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 14.r),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                        children: List.generate(markList.length, (index) {
                      MarkingTasks item = markList[index];
                      return InkWell(
                        onTap: (){
                          if(currentClass.id != item.id){
                            EasyLoading.show(status: 'loading...');
                            setState(() {
                              currentClass = item;
                            });
                            getStudentList();
                          }

                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              vertical: 5.r, horizontal: 10.r),
                          margin: EdgeInsets.only(
                              right: index < markList.length ? 8.r : 0),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4.r),
                          ),
                          child: Center(
                            child: Text(
                              '${widget.genderName}${item.className}',
                              style: TextStyle(
                                  fontSize: 10.sp,
                                  color: currentClass.id == item.id
                                      ? Color(0xFF6888FD)
                                      : Color(0xFF686868)),
                            ),
                          ),
                        ),
                      );
                    })),
                  ),
                ],
              ),
            ),
          SizedBox(
            height: 10.r,
          ),
          Container(
            height: 1.r,
            color: Color(0xFFCCCCCC),
          ),
          students.length>0? Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 14.r, horizontal: 14.r),
              child: EasyRefresh(
                firstRefresh: true,
                taskIndependence: true,
                controller: refreshController,
                header: MaterialHeader(),
                footer: TaurusFooter(),
                onRefresh: () async {
                  getStudentList();
                },
                child: students.length > 0
                    ? isPad()
                    ? GridView(
                  gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: 10.r,
                    crossAxisSpacing: 10.r,
                    childAspectRatio: 556 / 112,
                  ),
                  children: List.generate(students.length, (index) {
                    var item = students[index];
                    return InkWell(
                      onTap: (){
                        RouterManager.router.navigateTo(
                          context,
                          RouterManager.quickCheckPersonalPath +
                              '?jobId=${widget.jobId}&studentId=${item.studentId}',
                          transition: getTransition(),
                        );
                        // RouterManager.router.navigateTo(context,
                        //     '${RouterManager.jobPersonalDetailPath}?studentId=${item.studentId}&studentName=${Uri.encodeComponent(item.studentName)}');
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 10.r),
                        decoration: BoxDecoration(
                          borderRadius:
                          BorderRadius.all(Radius.circular(10.r)),
                          color: Colors.white,
                        ),
                        child: Row(
                          mainAxisAlignment:
                          MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                                child: Text(
                                  item.studentName,
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFF6888FD)),
                                )),

                         Container(
                                height: 20.r,
                                width: 70.r,
                                decoration: BoxDecoration(
                                  border: Border.all(width: 1.r,color: Color(0xFFFFA41E)),
                                  borderRadius: BorderRadius.all(Radius.circular(20.r)),

                                ),
                                child: Center(child: Text('详情',style: TextStyle(fontSize: 10.r,color: Color(0xFFFFA41E))),
                                )),
                          ],
                        ),
                      ),
                    );
                  }),
                )
                    : ListView.builder(
                  itemBuilder: (context, index) {
                    var item = students[index];
                    return InkWell(
                      onTap: (){
                        RouterManager.router.navigateTo(
                          context,
                          RouterManager.quickCheckPersonalPath +
                              '?jobId=${widget.jobId}&studentId=${item.studentId}',
                          transition: getTransition(),
                        );
                        // RouterManager.router.navigateTo(context,
                        //     '${RouterManager.jobPersonalDetailPath}?studentId=${item.studentId}&studentName=${Uri.encodeComponent(item.studentName)}');
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 20.r, horizontal: 15.r),
                        margin: EdgeInsets.only(bottom: 15.r),
                        decoration: BoxDecoration(
                          borderRadius:
                          BorderRadius.all(Radius.circular(10.r)),
                          color: Colors.white,
                        ),
                        child: Row(
                          mainAxisAlignment:
                          MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                                child: Text(
                                  item.studentName,
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFF6888FD)),
                                )),
                            Container(
                                height: 24.r,
                                width: 72.r,
                                decoration: BoxDecoration(
                                  border: Border.all(width: 1.r,color: Color(0xFFFFA41E)),
                                  borderRadius: BorderRadius.all(Radius.circular(20.r)),

                                ),
                                child: Center(child: Text('详情',style: TextStyle(fontSize: 10.r,color: Color(0xFFFFA41E))),
                                )),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: students.length,
                )
                    : MyEmptyWidget(),
              ),
            ),
          ):MyEmptyWidget(),
        ],
      ),
    );
  }
}
