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_level_set_params.dart';
import 'package:marking_app/common/model/job/job_review_submission.dart';
import 'package:marking_app/common/model/job/job_student_level.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 JobPriorityReviewSet extends StatefulWidget {
  final String groupId;
  const JobPriorityReviewSet({Key? key,required this.groupId}) : super(key: key);

  @override
  State<JobPriorityReviewSet> createState() => _JobPriorityReviewSetState();
}

class _JobPriorityReviewSetState extends State<JobPriorityReviewSet>
    with CommonMixin,SingleTickerProviderStateMixin {
  late final EasyRefreshController refreshController;
  late TabController tabController;
  int tabIndex = 0;
  List levelList = [];
  bool isClicking = false;

  @override
  void initState() {
    super.initState();
    EasyLoading.show(status: 'loading...');
    refreshController = EasyRefreshController();
    tabController =
        TabController(initialIndex: tabIndex, length: 2, vsync: this);
    getReadLevel();
  }

  void getReadLevel() async{
    RestClient _client = await getClient();
    BaseStructureResult<List<JobStudentLevel>> res = await _client.getJobReadLevel(widget.groupId,tabIndex == 0?1:0);
    setState(() {
      if(res.success){
        levelList = res.data!;
        isClicking = false;
      }else{
        levelList = [];
      }
    });
    EasyLoading.dismiss();
    refreshController.finishRefresh();
  }

  void setJobReadLevel(int studentId,int level) async{
    RestClient _client = await getClient();
    JobLevelSetParams params = JobLevelSetParams(studentId, level);
        BaseStructureResult res = await _client.getSetJobReadLevel(params);
        if(res.code == 200){
          getReadLevel();

        }
  }

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

  @override
  Widget build(BuildContext context) {
    bool isPadFlag = isPad();
    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(),
        ),
      ),
      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...');
                getReadLevel();
              },
              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.symmetric(vertical:14.r,horizontal: 14.r),
              child: EasyRefresh(
                firstRefresh: true,
                taskIndependence: true,
                controller: refreshController,
                header: MaterialHeader(),
                footer: TaurusFooter(),
                onRefresh: () async{
                  getReadLevel();
                },
                child: levelList.length>0?isPadFlag?GridView(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 10.r,
                  crossAxisSpacing: 10.r,
                  childAspectRatio: 556 / 112,
                ),children: List.generate(levelList.length, (index) {
                  JobStudentLevel item = levelList[index];
                  return 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)),)),
                       
                        tabIndex == 0?InkWell(
                          onTap: (){
                            setState(() {
                              isClicking = true;
                            });
                            setJobReadLevel(item.studentGroupDetailId,0);
                            EasyLoading.show(status: 'loading...');
                          },
                          child: Container(
                            height: 20.r,
                            width: 70.r,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                              color: isClicking?Color(0xFFDCE3FF):Color(0xFF6888FD),
                            ),
                            child: Center(
                              child:Text('取消优先',style: TextStyle(fontSize: 10.sp,color: Colors.white),),
                            ),
                          ),
                        ):InkWell(
                          onTap: (){
                            setState(() {
                              isClicking = true;
                            });
                            setJobReadLevel(item.studentGroupDetailId,1);
                            EasyLoading.show(status: 'loading...');
                          },
                          child: Container(
                            height: 20.r,
                            width: 70.r,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                              color: isClicking?Color(0xFF6888FD):Color(0xFFFFFFFF),
                              border: Border.all(width: 1.r,color: isClicking?Color(0xFFFFFFFF):Color(0xFF6888FD)),
                            ),
                            child: Center(
                              child:Text('设为优先',style: TextStyle(fontSize: 10.sp,color: isClicking?Color(0xFFFFFFFF):Color(0xFF6888FD)),),
                            ),
                          ),
                        ),
                        SizedBox(width: 5.r,),
                        InkWell(
                          onTap: (){
                            RouterManager.router.navigateTo(context, '${RouterManager.jobPersonalDetailPath}?studentId=${item.studentId}&studentName=${Uri.encodeComponent(item.studentName)}');
                          },
                          child: Container(
                            height: 20.r,
                            width: 70.r,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                              color: Colors.white,
                              border: Border.all(width: 1.r,color: Color(0xFFFCA017))
                            ),
                            child: Center(
                              child: Text('详情',style: TextStyle(fontSize: 10.sp,color: Color(0xFFFCA017)),),
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                }),):ListView.builder(itemBuilder: (context,index){
                  JobStudentLevel item = levelList[index];
                  return 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)),)),
                        tabIndex == 0?InkWell(
                          onTap: (){
                            setState(() {
                              isClicking = true;
                            });
                            setJobReadLevel(item.studentGroupDetailId,0);
                            EasyLoading.show(status: 'loading...');
                          },
                          child: Container(
                            height: 24.r,
                            width: 82.r,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                              color: isClicking?Color(0xFFDCE3FF):Color(0xFF6888FD),
                            ),
                            child: Center(
                              child:Text('取消优先',style: TextStyle(fontSize: 10.sp,color: Colors.white),),
                            ),
                          ),
                        ):InkWell(
                          onTap: (){
                            setJobReadLevel(item.studentGroupDetailId,1);
                            EasyLoading.show(status: 'loading...');
                          },
                          child: Container(
                            height: 24.r,
                            width: 82.r,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                              color: Color(0xFFFFFFFF),
                              border: Border.all(width: 1.r,color: Color(0xFF6888FD)),
                            ),
                            child: Center(
                              child:Text('设为优先',style: TextStyle(fontSize: 10.sp,color: Color(0xFF6888FD)),),
                            ),
                          ),
                        ),
                        SizedBox(width: 5.r,),
                        InkWell(
                          onTap: (){
                            RouterManager.router.navigateTo(context, '${RouterManager.jobPersonalDetailPath}?studentId=${item.studentId}&studentName=${Uri.encodeComponent(item.studentName)}');
                          },
                          child: Container(
                            height: 20.r,
                            width: 70.r,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(20.r)),
                                color: Colors.white,
                                border: Border.all(width: 1.r,color: Color(0xFFFCA017))
                            ),
                            child: Center(
                              child: Text('详情',style: TextStyle(fontSize: 10.sp,color: Color(0xFFFCA017)),),
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                },itemCount: levelList.length,):MyEmptyWidget(),
              ),
            ),
          )
        ],
      ),
    );
  }
}

