import 'dart:convert';

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:marking_app/common/config/request_config.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_page_data.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/job/job_student_goups.dart';
import 'package:marking_app/common/model/job/job_task_item.dart';
import 'package:marking_app/common/model/marking/marking_list_params.dart';
import 'package:marking_app/components/ReturnToHomepage.dart';
import 'package:marking_app/pages/homework_correction/widget/answer_trajectory_job.dart';
import 'package:marking_app/pages/homework_correction/widget/student_group_list.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/fast_data.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client.dart';

class AnswerTrajectory extends StatefulWidget {
  const AnswerTrajectory({Key? key}) : super(key: key);

  @override
  State<AnswerTrajectory> createState() => _AnswerTrajectoryState();
}

class _AnswerTrajectoryState extends State<AnswerTrajectory>
    with CommonMixin, SingleTickerProviderStateMixin {
  late final EasyRefreshController refreshController;
  late final EasyRefreshController refreshController2;
  late String loginName;
  List studentGroups = [];
  List<JobTaskItem> jobList = [];
  late TabController tabController;
  int tabIndex = 0;
  int page = 1;
  int pageSize = 10;
  int total = 0;

  @override
  void initState() {
    super.initState();
    refreshController = EasyRefreshController();
    refreshController2 = EasyRefreshController();
    tabController =
        TabController(initialIndex: tabIndex, length: 2, vsync: this);
    FastData fastData = FastData.getInstance();
    fastData.getUser().then((value) {
      if (value == null || value == '') return;
      Map<String, dynamic> userInfo = json.decode(value);
      setState(() {
        loginName = userInfo['loginName'];
      });
      getStudentGroups();
      getWorkList();
    });
  }

  void getStudentGroups() async {
    RestClient _client = await getClient();
    BaseStructureResult<List<JobStudentGroups>> res =
        await _client.getJobLevelStudentGroups(loginName);
    setState(() {
      if (res.code == 200) {
        studentGroups = res.data!;
      } else {
        studentGroups = [];
      }
    });
    refreshController.finishRefresh();
    EasyLoading.dismiss();
  }

  void goNextPage(id, title) {
    RouterManager.router.navigateTo(context,
        '${RouterManager.jobPriorityReviewSetPath}?&groupId=$id&title=${Uri.encodeComponent(title)}&page=answerTrajectory',
        transition: getTransition());
  }

  void getWorkList() async {
    final MarkingListParams params = MarkingListParams(
      page: page,
      limit: pageSize,
      pageType: 0,
      markingType: 1,
    );
    print('params=${params.limit}&page=${params.page}');
    RestClient client = await getClient();
    BaseStructureResult<BasePageData<JobTaskItem>> res =
        await client.getJobsByPage(params);
    List<JobTaskItem> arr = [];
    if (res.success) {
      if (page == 1) {
        arr = res.data!.items;
      } else {
        arr = [...jobList, ...res.data!.items];
      }
      total = res.data!.total;
    } else {
      jobList = [];
    }
    jobList = arr;
    setState(() {});
    refreshController2.finishRefresh();
    EasyLoading.dismiss();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(245, 245, 245, 1),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          '答题轨迹',
          style: TextStyle(fontSize: 14.sp, color: Color(0xFF333333)),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          ReturnToHomepage(),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 10.r,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 14.r),
            decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1.r, color: Color(0xFFCCCCCC)))),
            child: TabBar(
              onTap: (int val) {
                print(val);
                setState(() {
                  tabIndex = val;
                });
                /*EasyLoading.show(status: 'loading...');
                if(val == 0){
                  getStudentGroups();
                }*/
              },
              tabs: [
                SizedBox(
                  width: (MediaQuery.of(context).size.width - 28.r) / 2,
                  child: Tab(
                    text: '按学生',
                  ),
                ),
                SizedBox(
                  width: (MediaQuery.of(context).size.width - 28.r) / 2,
                  child: Tab(
                    text: '按作业',
                  ),
                )
              ],
              controller: tabController,
              unselectedLabelStyle:
                  TextStyle(fontSize: 14.sp, color: Color(0xFF666666)),
              labelStyle: TextStyle(
                fontSize: 14.sp,
                color: Color(0xFF6888FD),
              ),
              isScrollable: true,
              labelColor: Color(0xFF6888FD),
              unselectedLabelColor: Color(0xFF666666),
              indicatorSize: TabBarIndicatorSize.label,
              labelPadding: const EdgeInsets.all(0),
            ),
          ),
           Expanded(
                  child: Padding(
                    padding:
                        EdgeInsets.only(top: 15.r, left: 14.r, right: 14.r),
                    child:
                    tabIndex == 0
                        ?
                    EasyRefresh(
                      firstRefresh: false,
                      taskIndependence: true,
                      controller: refreshController,
                      header: MaterialHeader(),
                      footer: TaurusFooter(),
                      onRefresh: () async {
                        getStudentGroups();
                      },
                      child: StudentGroupList(studentGroups, goNextPage,
                          rightBtn: Container(
                            margin: EdgeInsets.only(left: 5.r),
                            height: 20.r,
                            width: 55.r,
                            decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20.r)),
                              border: Border.all(
                                  width: 1.r, color: Color(0xFFFF9800)),
                            ),
                            child: Center(
                              child: Text(
                                '详情',
                                style: TextStyle(
                                    fontSize: 10.sp, color: Color(0xFFFF9800)),
                              ),
                            ),
                          )),
                    ):EasyRefresh(
                        firstRefresh: false,
                        taskIndependence: true,
                        controller: refreshController2,
                        header: MaterialHeader(),
                        footer: TaurusFooter(),
                        onRefresh: () async {
                          page = 1;
                          setState(() {});
                          getWorkList();
                        },
                        onLoad: () async {
                          if (jobList.length < total) {
                            EasyLoading.show(status: 'loading...');
                            page = page + 1;
                            getWorkList();
                          }
                        },
                        child:AnswerTrajectoryJob(jobList)),
                  ),
                )
        ],
      ),
    );
  }
}
