import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.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_fav_student.dart';
import 'package:marking_app/common/model/job/job_favorite_item_model.dart';
import 'package:marking_app/common/model/job/job_report_join_class.dart';
import 'package:marking_app/components/ReturnToHomepage.dart';
import 'package:marking_app/pages/homework_correction/pages/favorite_student_dialog.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.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';

part 'job_favorite.g.dart';

/// 作业收藏学生名单列表
class JobFavorite extends StatefulWidget {
  final int jobId;
  final int? schoolId;
  final int? gradeId;
  final String? className;
  final String jobName;

  const JobFavorite({
    required this.jobId,
    this.schoolId,
    this.gradeId,
    this.className,
    required this.jobName,
    super.key,
  });

  @override
  State<JobFavorite> createState() => _JobFavoriteState();
}

class _JobFavoriteState extends State<JobFavorite> with CommonMixin {
  late Future<List<Items>?> _future;
  List<JobReportJoinClass>? involveClasses = [];
  JobReportJoinClass? classData;
  late String loginName;
  final int pageSize = 100;
  String className = '全部';

  @override
  void initState() {
    super.initState();
    /* FastData fastData = FastData.getInstance();
    fastData.getUser().then((value) {
      if (value == null || value == '') return;
      Map<String, dynamic> userInfo = json.decode(value);
      setState(() {
        loginName = userInfo['loginName'];
      });
    });*/
    if (widget.className != null) {
      className = widget.className!;
    }

    getInvolveClasses();
    _future = getData();
  }

  Future<List<Items>> getData() async {
    var _client = await getClient();
    var result = await _client.getListOfJobFavorites(widget.jobId,
        widget.jobName, className == '全部' ? '' : className, pageSize);
    return result.data!.items;
  }

  Future<void> toGoCancelFavorite(int jobId, int studentId) async {
    var _client = await getClient();
    var result = await _client.toJobCancelFavorite(jobId, studentId);
    if (result.success && (result.data ?? false)) {
      _future = getData();
    }
  }

  Future<void> getInvolveClasses() async {
    try {
      RestClient _client = await getClient();
      BaseStructureResult<List<JobReportJoinClass>> result =
          await _client.getJobReportJoinClasses(widget.jobId);
      if (result.success) {
        toUpState(setState, () {
          involveClasses = [
            JobReportJoinClass(-1, '全部', -1, '全部', '全部', '全部', -1, -1, '-1'),
            ...(result.data ?? [])
          ];
          involveClasses?.forEach((element) {
            if (element.className == widget.className &&
                element.gradeId == widget.gradeId &&
                element.schoolId == widget.schoolId) {
              classData = element;
            }
          });
        }, mounted);
      }
      _future = getData();
    } catch (e) {
      print(e);
    }
  }

  Future<bool> confirmDialog() async {
    return await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        actionsPadding: EdgeInsets.symmetric(vertical: 10.r, horizontal: 10.r),
        content: Text(
          '确定删除吗？',
          style: TextStyle(fontSize: 14.sp, color: Color(0xFF505E6E)),
        ),
        actionsAlignment: MainAxisAlignment.center,
        actions: <Widget>[
          InkWell(
            child: Container(
                width: 97.r,
                height: 27.r,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(20.r)),
                  color: Color(0xFF6888FD),
                ),
                child: Center(
                    child: Text(
                  '确定',
                  style: TextStyle(color: Colors.white),
                ))),
            onTap: () {
              // 执行操作
              Navigator.of(context).pop(true);
            },
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop(false);
            },
            child: Container(
                width: 97.r,
                height: 27.r,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(20.r)),
                  color: Color(0xFFF4F4F4),
                ),
                child: Center(
                    child: Text(
                  '取消',
                  style: TextStyle(color: Color(0xFF666666)),
                ))),
          ),
        ],
      ),
    );
  }

  getDelete(Items student) async {
    RestClient _client = await getClient();
    BaseStructureResult res = await _client.getJobDeFavorites(
        widget.jobId, student.studentId, student.questionPage!);
    if (res.success) {
      _future = getData();
      setState(() {});
    }
  }

  void showStudentDialog(BuildContext context, Items item, List groups) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
            insetPadding: EdgeInsets.all(25.r),
            content: FavoriteStudentDialog(
                item: item,
                group: groups,
                deleteFav: getDelete,
                confirmDialog: confirmDialog),
            contentPadding: EdgeInsets.all(0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(15.r))));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    bool isPadFlag = isPad();
    return Scaffold(
      backgroundColor: Color.fromRGBO(245, 245, 245, 1),
      appBar: AppBar(
        // titleSpacing: 0,
        elevation: 0.0,
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () => Navigator.of(context).pop()),
        iconTheme: IconThemeData(color: Colors.black),
        title: quickText('收藏夹'),
        centerTitle: true,
        backgroundColor: Colors.white,
        actions: [
          ReturnToHomepage(),
        ],
      ),
      body: MyFutureBuilder.buildFutureBuilderOfSingleInstance<List<Items>>(
        context,
        _future,
        (List<Items>? datas) {
          if (datas == null)
            return Container(
              child: InkWell(
                onTap: () {
                  toUpState(setState, () => _future = getData(), mounted);
                },
                child: Center(
                  child: quickText('请求错误,点击再次发起请求'),
                ),
              ),
            );
          List pageList = [];
          List groupList = [];
          if (datas!.length > 0) {
            for (var item in datas) {
              pageList.add(item.questionPage);
            }
            pageList = pageList.toSet().toList();

            for (var page in pageList) {
              var printList = datas
                  .where((element) => element.questionPage == page)
                  .toList();
              groupList.add({"questionPage": page, "list": printList});
            }
            groupList
                .sort((a, b) => a['questionPage'].compareTo(b['questionPage']));
          }
          return Container(
              child: Column(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(vertical: 0.r, horizontal: 14.r),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      widget.jobName,
                      style:
                          TextStyle(fontSize: 14.sp, color: Color(0xFF3C3C3C)),
                    ),
                    // 下拉框
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: 10.h, horizontal: 10.w),
                      child: Row(
                        children: [
                          $classSelection(involveClasses, classData,
                              call: (JobReportJoinClass _classData) {
                            classData = _classData;
                            if (_classData.gradeId == -1) classData = null;
                            className = _classData.className;
                            _future = getData();
                            toUpState(setState, () {}, mounted);
                          }),
                          // Expanded(child: Text('')),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                height: 1.r,
                decoration: BoxDecoration(
                  color: Color(0xFFCCCCCC),
                ),
              ),
              groupList.length > 0
                  ? Expanded(
                      child: isPadFlag
                          ? Padding(
                              padding: EdgeInsets.only(
                                  top: 10.r,
                                  bottom: 8.r,
                                  left: 14.r,
                                  right: 14.r),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children:
                                      List.generate(groupList.length, (index) {
                                    var item = groupList[index];
                                    return Padding(
                                      padding: EdgeInsets.only(bottom: 8.r),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Padding(
                                            padding:
                                                EdgeInsets.only(bottom: 5.r),
                                            child: Text(
                                              '第${item['questionPage']}页',
                                              style: TextStyle(
                                                  fontSize: 12.sp,
                                                  color: Color(0xFF2E5BFF)),
                                            ),
                                          ),
                                          GridView(
                                              gridDelegate:
                                                  SliverGridDelegateWithFixedCrossAxisCount(
                                                crossAxisCount: 2,
                                                mainAxisSpacing: 8.r,
                                                crossAxisSpacing: 10.r,
                                                childAspectRatio: 556 / 112,
                                              ),
                                              shrinkWrap: true,
                                              children: List.generate(
                                                  item['list'].length, (i) {
                                                Items student = item['list'][i];
                                                return Container(
                                                  padding: EdgeInsets.symmetric(
                                                      vertical: 5.r,
                                                      horizontal: 10.r),
                                                  decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                6.r)),
                                                  ),
                                                  child: InkWell(
                                                    onTap: () {
                                                      showStudentDialog(context,
                                                          student, groupList);
                                                    },
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        quickText(
                                                            student.studentName,
                                                            color: Color(
                                                                0xFF333333),
                                                            size: 12.sp),
                                                        Expanded(
                                                            child: Container()),
                                                        Padding(
                                                          padding:
                                                              EdgeInsets.only(
                                                                  right: 8.r),
                                                          child: Text(
                                                            student.className,
                                                            style: TextStyle(
                                                                fontSize: 12.sp,
                                                                color: Color(
                                                                    0xFF666666)),
                                                          ),
                                                        ),
                                                        InkWell(
                                                          onTap: () async {
                                                            var confim =
                                                                await confirmDialog();
                                                            if (confim) {
                                                              getDelete(
                                                                  student);
                                                            }
                                                          },
                                                          child: Image.asset(
                                                            'assets/images/favorite_delete_icon.png',
                                                            width: 24.r,
                                                            height: 24.r,
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                );
                                              })),
                                        ],
                                      ),
                                    );
                                  })),
                            )
                          : ListView.builder(
                              shrinkWrap: true,
                              itemBuilder: (context, index) {
                                var item = groupList[index];
                                return Padding(
                                  padding: EdgeInsets.only(
                                      top: 10.r,
                                      bottom: 8.r,
                                      left: 14.r,
                                      right: 14.r),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: EdgeInsets.only(bottom: 5.r),
                                        child: Text(
                                          '第${item['questionPage']}页',
                                          style: TextStyle(
                                              fontSize: 14.sp,
                                              color: Color(0xFF2E5BFF)),
                                        ),
                                      ),
                                      ListView.builder(
                                        itemBuilder: (context, i) {
                                          Items student = item['list'][i];
                                          return InkWell(
                                            onTap: () {
                                              showStudentDialog(
                                                  context, student, groupList);
                                            },
                                            child: Container(
                                              padding: EdgeInsets.symmetric(
                                                  vertical: 5.r,
                                                  horizontal: 10.r),
                                              margin: EdgeInsets.only(top: 5.r),
                                              decoration: BoxDecoration(
                                                color: Colors.white,
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(6.r)),
                                              ),
                                              child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  quickText(student.studentName,
                                                      color: Color(0xFF333333),
                                                      size: 14.sp),
                                                  Expanded(child: Container()),
                                                  Padding(
                                                    padding: EdgeInsets.only(
                                                        right: 8.r),
                                                    child: Text(
                                                      student.className,
                                                      style: TextStyle(
                                                          fontSize: 14.sp,
                                                          color: Color(
                                                              0xFF666666)),
                                                    ),
                                                  ),
                                                  InkWell(
                                                    onTap: () async {
                                                      var confim =
                                                          await confirmDialog();
                                                      if (confim) {
                                                        getDelete(student);
                                                      }
                                                    },
                                                    child: Image.asset(
                                                      'assets/images/favorite_delete_icon.png',
                                                      width: 32.r,
                                                      height: 32.r,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          );
                                        },
                                        itemCount: item['list'].length,
                                        shrinkWrap: true,
                                      ),
                                    ],
                                  ),
                                );
                              },
                              itemCount: groupList.length,
                            ),
                    )
                  : Padding(
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).size.height / 2 - 200.r),
                      child: MyEmptyWidget(),
                    ),
            ],
          ));
        },
      ),
    );
  }
}

/// 下拉选择框
@swidget
Widget $classSelection(
    List<JobReportJoinClass>? involveClasses, JobReportJoinClass? classData,
    {required Function(JobReportJoinClass) call}) {
  if (involveClasses == null)
    return Container(child: quickText('点击重试')); // 点击重试
  return Container(
    // width: 200.r,
    padding: EdgeInsets.symmetric(horizontal: 10.r),
    decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(
          top: Radius.elliptical(10, 10),
          bottom: Radius.elliptical(10, 10),
        )),
    child: DropdownButton(
      value: classData?.uniqueId ?? '-1',

      style: TextStyle(color: Color.fromRGBO(89, 89, 89, 1), fontSize: 12.sp),
      underline: Container(),
      // isExpanded:true,
      items: involveClasses.map((e) {
        return DropdownMenuItem(
          value: e.uniqueId!,
          child: quickText(
              e.uniqueId == '-1'
                  ? e.graduationYear
                  : e.graduationYear + e.className,
              size: 10.sp,
              color: Colors.black),
        );
      }).toList(),
      onChanged: (String? value) {
        if (value == null) return;
        call(involveClasses.firstWhere((element) => element.uniqueId == value));
      },
    ),
  );
}
