import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.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_concerned_with_student.dart';
import 'package:marking_app/common/model/job/job_task_item.dart';
import 'package:marking_app/routes/RouterManager.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';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:badges/badges.dart' as badges;

part 'homework_tasks_view_item.g.dart';

// 作业任务单个试题视图
class HomeworkTasksViewItem extends StatelessWidget with CommonMixin {
  final bool completed; // 已完成
  final VoidCallback call;
  final JobTaskItem jobTaskItem;
  const HomeworkTasksViewItem({required this.jobTaskItem, required this.call, this.completed = true, super.key});

  // 结束批阅方法
  Future<bool> endReview(List<MarkingTasks> markingTasks) async {
    try {
      ToastUtils.showLoading();
      RestClient client = await getClient();
      BaseStructureResult res = await client.toEndReviewJob(markingTasks.map((e) => e.id).toList());
      if (!res.success) ToastUtils.showError('结束失败，请重试');
      return res.success;
    } catch (e) {
      ToastUtils.showError('结束失败，请重试');
      return false;
    }
  }

  /// @name showStudents
  /// @param {List<int>}  taskId      子任务ID集合
  /// @param {String}     taskName    主任务名称
  /// @param {bool}       className   班级名称（不传此参数为主任务；传此参数为子任务）
  /// @param {bool}       submitted   是否已提交(默认未提交)
  Future<void> showStudents(
    BuildContext context, [
    bool? submitted = false,
    String? className,
  ]) async {
    ToastUtils.showLoading();
    List<JobConcernedWithStudent> students = [];
    // try {
    //   RestClient _client = await getClient();
    //   BaseStructureResult<List<JobConcernedWithStudent>> _result = await _client.getJobWithStudents(
    //     JobConcernedWithStudentParams(taskIds, isCommit: submitted),
    //   );
    //   if (!_result.success) {
    //     return ToastUtils.showError(_result.message ?? '获取学生列表失败');
    //   }
    //   if (_result.data?.isEmpty ?? true) {
    //     return ToastUtils.showError('获取到的学生列表为空');
    //   }
    //   students = _result.data!;
    // } catch (e) {
    //   return ToastUtils.showError('获取学生列表失败');
    // } finally {
    //   ToastUtils.dismiss();
    // }

    showModalBottomSheet(
      context: context,
      elevation: 10,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      builder: (BuildContext context) {
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 2.w),
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 14.h),
                child: quickText(
                  '${className ?? ''}${submitted! ? '已提交' : '未提交'}作业学生',
                  size: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Color.fromRGBO(60, 60, 60, 1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 4.w),
                  children: [
                    Wrap(
                      spacing: 6.0, // 主轴(水平)方向间距
                      runSpacing: 4.0, // 纵轴（垂直）方向间距
                      alignment: WrapAlignment.spaceAround, //沿主轴方向居中
                      children: students.map((e) {
                        return Chip(
                          backgroundColor: Color.fromRGBO(239, 242, 255, 1),
                          avatar: CircleAvatar(
                            backgroundColor: Colors.white,
                            child: quickText(e.studentName.substring(0, 1),
                                size: 12.sp, color: Theme.of(context).primaryColor),
                          ),
                          label: quickText(e.studentName, color: Color.fromRGBO(80, 94, 110, 1), size: 12.sp),
                        );
                      }).toList(),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return completed
        ? $CompletedHomeworkView(jobTaskItem: jobTaskItem, showStudentsCall: showStudents)
        : InkWell(
            onTap: () {
              String url =
                  '${RouterManager.jobListParticipateInClassPath}?&jobId=${jobTaskItem.id}&genderName=${Uri.encodeComponent(jobTaskItem.genderName)}&jobName=${Uri.encodeComponent(jobTaskItem.title)}';
              RouterManager.router.navigateTo(context, url, transition: getTransition()).then((value) {
                if (value != null && value == true) call();
              });
            },
            child: $UnfinishedHomework(jobTaskItem: jobTaskItem),
          );
  }
}

// 已完成
@hwidget
Widget $completedHomeworkView(BuildContext context,
    {required JobTaskItem jobTaskItem, required ShowStudentsCall showStudentsCall}) {
  return InkWell(
    onTap: () {
      String url =
          '${RouterManager.jobListParticipateInClassPath}?&jobId=${jobTaskItem.id}&genderName=${Uri.encodeComponent(jobTaskItem.genderName)}&jobName=${Uri.encodeComponent(jobTaskItem.title)}&completed=${true}';
      RouterManager.router.navigateTo(context, url, transition: getTransition());
    },
    child: Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 20.h),
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: const Color.fromRGBO(255, 255, 255, 1),
        boxShadow: [
          BoxShadow(
            color: const Color.fromRGBO(210, 216, 241, 1),
            offset: Offset.zero, //阴影y轴偏移量
            blurRadius: 5.8, //阴影模糊程度
            spreadRadius: 0, //阴影扩散程度
          )
        ],
      ),
      child: Column(
        children: [
          // 顶部任务名称
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: isPad() ? 32.w : 36.w,
                  height: 18.h,
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(left: isPad() ? 2.w : 3.w),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(104, 136, 253, 1),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(14.r),
                      topRight: Radius.circular(3.r),
                      bottomLeft: Radius.circular(4.r),
                      bottomRight: Radius.circular(4.r),
                    ),
                  ),
                  margin: EdgeInsets.only(right: 4.w),
                  child: quickText('作业', color: Colors.white, size: 10.sp),
                ),
                Expanded(
                  child: quickText(
                    jobTaskItem.title,
                    maxLines: 2,
                    size: 16.sp,
                    color: Color.fromRGBO(70, 70, 70, 1),
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
          ),

          SizedBox(height: 12.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                quickText(
                  jobTaskItem.createTime.substring(0, 10),
                  color: Color.fromRGBO(97, 97, 97, 1),
                  size: 12.sp,
                  fontWeight: FontWeight.w500,
                ),
                quickText(' / ', color: Color.fromRGBO(76, 199, 147, 1), size: 12.sp, fontWeight: FontWeight.w500),
                quickText(
                  '参与班级：${jobTaskItem.taskCount}',
                  color: Color.fromRGBO(76, 199, 147, 1),
                  size: 12.sp,
                  fontWeight: FontWeight.w600,
                ),
                quickText(' / ', color: Color.fromRGBO(116, 145, 253, 1), size: 12.sp, fontWeight: FontWeight.w500),
                quickText(
                  '科目：' + jobTaskItem.subjectName,
                  color: Color.fromRGBO(116, 145, 253, 1),
                  size: 12.sp,
                  fontWeight: FontWeight.w600,
                ),
                Expanded(child: SizedBox()),
                FavoriteButton(
                  jobTaskItem.id,
                  jobTaskItem.title,
                  margin: EdgeInsets.zero,
                  isRow: false,
                ),
              ],
            ),
          ),

          SizedBox(height: 20.h),
          Container(
            padding: EdgeInsets.symmetric(vertical: 10.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(6.r), bottomRight: Radius.circular(6.r)),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: const Color.fromRGBO(0, 0, 0, 0.15),
                  offset: Offset(0, -0.0001), //阴影y轴偏移量
                  blurRadius: 4, //阴影模糊程度
                  spreadRadius: 0, //阴影扩散程度
                )
              ],
            ),
            child: Row(children: [
              Expanded(
                  child: InkWell(
                onTap: () => easyThrottle('go_to_homework_report', () {
                  RouterManager.router.navigateTo(
                    context,
                    RouterManager.jobReportPagePath +
                        '?title=${Uri.encodeComponent(jobTaskItem.title)}&id=${jobTaskItem.id}',
                    transition: getTransition(),
                  );
                }),
                child: Container(
                  alignment: Alignment.center,
                  child: quickText('查看报告', color: Color.fromRGBO(118, 118, 118, 1), size: 13.sp),
                ),
              )),
            ]),
          ),
          // $CompletedHomeworkInfoBox(
          //   segmentation: false,
          //   showStudentsCall: showStudentsCall,
          //   unsubmittedQuantity: jobTaskItem.studentCount - jobTaskItem.commitStudentCount,
          //   submittedQuantity: jobTaskItem.commitStudentCount,
          //   precision: jobTaskItem.precision / 100,
          //   objectivePrecision: jobTaskItem.objectivePrecision / 100,
          //   subjectivePrecision: jobTaskItem.subjectivePrecision / 100,
          // ),
          // InkWell(
          //   onTap: () {
          //     RouterManager.router.navigateTo(
          //       context,
          //       RouterManager.jobReportPagePath + '?title=${Uri.encodeComponent(jobTaskItem.title)}&id=${jobTaskItem.id}',
          //       transition: getTransition(),
          //     );
          //   },
          //   child: Row(
          //     children: [
          //       Expanded(flex: 1, child: SizedBox()),
          //       Expanded(
          //         flex: 9,
          //         child: Container(
          //           alignment: Alignment.center,
          //           margin: EdgeInsets.only(top: 20.h),
          //           padding: EdgeInsets.symmetric(vertical: 7.h),
          //           decoration: BoxDecoration(
          //             borderRadius: BorderRadius.circular(20),
          //             gradient: LinearGradient(
          //               begin: Alignment.centerLeft,
          //               end: Alignment.centerRight,
          //               colors: [Color.fromRGBO(95, 197, 255, 1), Color.fromRGBO(61, 68, 255, 0.82)],
          //             ),
          //           ),
          //           child: quickText('查看报告', color: Colors.white, size: 12.sp),
          //         ),
          //       ),
          //       Expanded(flex: 1, child: SizedBox()),
          //     ],
          //   ),
          // )
        ],
      ),
    ),
  );
}

@hwidget
Widget $completedHomeworkChildView(
  BuildContext context, {
  required JobTaskItem jobTaskItem,
  required MarkingTasks taskItem,
  required ShowStudentsCall showStudentsCall,
}) {
  return Column(
    children: [
      SizedBox(height: 16.h),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          quickText(
            jobTaskItem.genderName + taskItem.className,
            color: Color.fromRGBO(255, 123, 1, 1),
            size: 14.sp,
            fontWeight: FontWeight.bold,
          ),
          quickText('题量：${taskItem.totalCount}', color: Color.fromRGBO(68, 68, 68, 1), size: 12.sp),
          quickText(taskItem.teacherName, color: Color.fromRGBO(68, 68, 68, 1), size: 12.sp),
          quickText(taskItem.finishTime?.substring(0, 16) ?? '', color: Color.fromRGBO(97, 97, 97, 1), size: 12.sp),
        ],
      ),
      SizedBox(height: 10.h),
      $CompletedHomeworkInfoBox(
        precision: taskItem.precision / 100,
        objectivePrecision: taskItem.objectivePrecision / 100,
        subjectivePrecision: taskItem.subjectivePrecision / 100,
        submittedQuantity: taskItem.commitStudentCount,
        unsubmittedQuantity: taskItem.studentCount - taskItem.commitStudentCount,
        showStudentsCall: showStudentsCall,
        className: taskItem.className,
      ),
    ],
  );
}

// 已完成作业按钮
@swidget
Widget $completedHomeworkBtn(
  BuildContext context, {
  required int submittedQuantity,
  required int unsubmittedQuantity,
  required ShowStudentsCall showStudentsCall,
  String? className,
}) {
  return Container(
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Expanded(
          child: Material(
            color: Colors.white,
            child: InkWell(
              onTap: () {
                if (unsubmittedQuantity <= 0) return ToastUtils.showInfo('没有未提交的作业');
                showStudentsCall(context, false, className);
              },
              borderRadius: BorderRadius.circular(8.r),
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 8.h),
                decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(104, 136, 253, 1), width: 1.r),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: quickText('未交作业：$unsubmittedQuantity份', size: 12.sp, color: Color.fromRGBO(104, 136, 253, 1)),
              ),
            ),
          ),
        ),
        SizedBox(width: 30.w),
        Expanded(
          child: Material(
            color: Colors.white,
            child: InkWell(
              onTap: () async {
                if (submittedQuantity <= 0) return ToastUtils.showInfo('没有已提交的作业');
                showStudentsCall(context, true, className);
              },
              borderRadius: BorderRadius.circular(8.r),
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 8.h),
                decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(76, 199, 147, 1), width: 1.r),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: quickText('已交作业：$submittedQuantity份', size: 12.sp, color: Color.fromRGBO(76, 199, 147, 1)),
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

@swidget
Widget $completedHomeworkProgressBar(
  BuildContext context, {
  required String title,
  required Color color,
  required double percent,
}) {
  var percentStr = '${doubleToStringAsFixed(percent * 100)}%';

  return Container(
    margin: EdgeInsets.symmetric(vertical: 10.h),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          alignment: Alignment.centerRight,
          child: Row(
            children: [
              if (title == '正确率：') quickText('正确率', color: Colors.transparent, size: 13.sp),
              quickText(title, color: Color.fromRGBO(139, 139, 139, 1), size: 13.sp),
            ],
          ),
        ),
        Expanded(
          flex: 1,
          child: Container(
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.r),
                      boxShadow: [
                        BoxShadow(
                          color: color,
                          spreadRadius: 0.6,
                          blurRadius: 3,
                          offset: Offset(0, 0),
                        ),
                      ],
                    ),
                    child: LinearPercentIndicator(
                      padding: EdgeInsets.zero,
                      animation: true,
                      lineHeight: 10.h,
                      animationDuration: 2500,
                      percent: percent,
                      center: Text(
                        percentStr,
                        style: TextStyle(color: Colors.white, fontSize: 8.sp),
                      ),
                      // linearStrokeCap: LinearStrokeCap.butt,
                      progressColor: color,
                      backgroundColor: Colors.white,
                      barRadius: Radius.circular(10.r),
                      // linearGradient: LinearGradient(
                      //   tileMode: TileMode.mirror,
                      //   stops: [0.0, 1.0],
                      //   colors: [color.withOpacity(0.1), color],
                      // ),
                    ),
                  ),
                ),
                SizedBox(width: 4.w),
                quickText(percentStr, size: 10.sp, color: color)
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

@swidget
Widget $completedHomeworkInfoBox(
  BuildContext context, {
  required int unsubmittedQuantity,
  required int submittedQuantity,
  required double objectivePrecision, // 客观题正确率
  required double subjectivePrecision, // 主观题正确率
  required double precision, // 综合正确率
  required ShowStudentsCall showStudentsCall,
  bool segmentation = true,
  String? className,
}) {
  return Column(
    children: [
      $CompletedHomeworkBtn(
        className: className,
        unsubmittedQuantity: unsubmittedQuantity,
        submittedQuantity: submittedQuantity,
        showStudentsCall: showStudentsCall,
      ),
      SizedBox(height: 10.h),
      $CompletedHomeworkProgressBar(
        color: Color.fromRGBO(76, 199, 147, 1),
        percent: objectivePrecision,
        title: '客观题正确率：',
      ),
      $CompletedHomeworkProgressBar(
        color: Color.fromRGBO(255, 190, 91, 1),
        percent: subjectivePrecision,
        title: '主观题正确率：',
      ),
      $CompletedHomeworkProgressBar(
        color: Color.fromRGBO(166, 139, 242, 1),
        percent: precision,
        title: '正确率：',
      ),
      if (segmentation)
        Container(
          height: 1.h,
          decoration: BoxDecoration(color: Color.fromRGBO(233, 233, 233, 1)),
        ),
    ],
  );
}

// 未完成作业单个view
@swidget
Widget $unfinishedHomework(BuildContext context, {required JobTaskItem jobTaskItem}) {
  return Stack(
    alignment: const FractionalOffset(0.95, 0),
    children: [
      Container(
        margin: EdgeInsets.only(bottom: 16.h),
        child: Column(
          children: [
            SizedBox(height: 30.h),
            Container(
              padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 10.w),
              width: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.r),
                color: const Color.fromRGBO(255, 255, 255, 1),
                boxShadow: [
                  BoxShadow(
                    color: const Color.fromRGBO(210, 216, 241, 1),
                    offset: Offset.zero, //阴影y轴偏移量
                    blurRadius: 5.8, //阴影模糊程度
                    spreadRadius: 0, //阴影扩散程度
                  )
                ],
              ),
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: isPad() ? 32.w : 38.w,
                          height: 18.h,
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(left: isPad() ? 2.w : 3.w),
                          decoration: BoxDecoration(
                            color: jobTaskItem.markingTypeEnum.name == '作业'
                                ? const Color.fromRGBO(104, 136, 253, 1)
                                : const Color.fromRGBO(255, 175, 56, 1),
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(14.r),
                              topRight: Radius.circular(3.r),
                              bottomLeft: Radius.circular(4.r),
                              bottomRight: Radius.circular(4.r),
                            ),
                          ),
                          margin: EdgeInsets.only(right: 4.w),
                          child: quickText(jobTaskItem.markingTypeEnum.name, color: Colors.white, size: 10.sp),
                        ),
                        Expanded(
                          child: quickText(
                            jobTaskItem.title,
                            maxLines: 2,
                            size: isPad() ? 14.sp : 16.sp,
                            color: Color.fromRGBO(70, 70, 70, 1),
                            fontWeight: FontWeight.bold,
                          ),
                        )
                      ],
                    ),
                    SizedBox(height: 10.h),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        quickText(
                          jobTaskItem.subjectName,
                          color: Color.fromRGBO(97, 97, 97, 1),
                          size: 12.sp,
                        ),
                        quickText(' / ',
                            color: Color.fromRGBO(130, 130, 130, 1), size: 11.sp, fontWeight: FontWeight.w500),
                        Container(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              quickText('题量：', color: Color.fromRGBO(130, 130, 130, 1), size: 11.sp),
                              quickText(
                                jobTaskItem.totalCount,
                                color: Color.fromRGBO(97, 97, 97, 1),
                                size: 13.sp,
                              ),
                            ],
                          ),
                        ),
                        quickText(' / ',
                            color: Color.fromRGBO(130, 130, 130, 1), size: 11.sp, fontWeight: FontWeight.w500),
                        quickText(jobTaskItem.createTime.substring(0, 16),
                            color: Color.fromRGBO(97, 97, 97, 1), size: 12.sp),
                      ],
                    ),
                    FavoriteButton(jobTaskItem.id, jobTaskItem.title),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      Container(
        padding: EdgeInsets.all(9.r),
        decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white),
        child: CircularPercentIndicator(
          radius: 40.r,
          lineWidth: 10.r,
          animation: true,
          percent: jobTaskItem.progressPercentage / 100,
          center: Text.rich(TextSpan(children: [
            TextSpan(
              text: getDoubleRemoveZero(jobTaskItem.progressPercentage, '0'),
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16.sp,
                color: Theme.of(context).primaryColor,
              ),
            ),
            TextSpan(
              text: "%",
              style: TextStyle(color: Color.fromRGBO(70, 70, 70, 1), fontSize: 12.sp, fontWeight: FontWeight.bold),
            ),
          ])),
          circularStrokeCap: CircularStrokeCap.round,
          // progressColor: Theme.of(context).primaryColor,
          linearGradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            tileMode: TileMode.clamp,
            stops: [0.0, 1.0],
            colors: [
              Theme.of(context).primaryColor.withOpacity(0.1),
              Theme.of(context).primaryColor,
            ],
          ),
          backgroundColor: Color.fromRGBO(244, 244, 244, 1),
        ),
      ),
    ],
  );
}

typedef EndReviewCall = Future<bool> Function(List<MarkingTasks> markingTasks);
typedef ShowStudentsCall = Future<void> Function(
  BuildContext context, [
  bool? submitted,
  String? className,
]);

class FavoriteButton extends StatefulWidget {
  final int jobId;
  final String jobName;
  final bool isRow;
  final EdgeInsets? margin;
  const FavoriteButton(this.jobId, this.jobName, {this.margin, this.isRow = true, super.key});

  @override
  State<FavoriteButton> createState() => _FavoriteButtonState();
}

class _FavoriteButtonState extends State<FavoriteButton> with CommonMixin {
  late Future<int> _future; // 考试试卷

  Future<int> getInvolveClasses() async {
    print('我的收藏请求数据');
    try {
      RestClient _client = await getClient();
      var result = await _client.getListOfJobFavoriteNumber(widget.jobId);

      if (result.success && (result.data?.isNotEmpty ?? false)) {
        return result.data!.map((e) => e.count).reduce((value, element) => value + element);
      }
    } catch (e) {
      print(e);
    }
    return 0;
  }

  // 收藏夹
  void bookmarks(BuildContext context) {
    RouterManager.router
        .navigateTo(
      context,
      RouterManager.jobFavoritePagePath + '?jobId=${widget.jobId}&jobName=${Uri.encodeComponent(widget.jobName)}',
      transition: getTransition(),
    )
        .then((value) {
      toUpState(setState, () {}, mounted);
    });
  }

  @override
  void initState() {
    super.initState();
    // _future = getInvolveClasses();
  }

  @override
  Widget build(BuildContext context) {
    var margin = widget.margin ?? EdgeInsets.only(top: 15.h);
    return FutureBuilder<int>(
      builder: (context, AsyncSnapshot<int> async) {
        //在这里根据快照的状态，返回相应的widget
        if (async.connectionState == ConnectionState.active || async.connectionState == ConnectionState.waiting) {
          return Container();
        }
        if (async.connectionState == ConnectionState.done) {
          var favoriteNumber = async.data;
          if (favoriteNumber == null || favoriteNumber <= 0) return Container();

          return widget.isRow
              ? Row(
                  children: [
                    Container(
                      margin: margin,
                      child: Material(
                        color: Color.fromRGBO(244, 244, 244, 1),
                        borderRadius: BorderRadius.circular(20.r),
                        child: InkWell(
                          onTap: () => bookmarks(context),
                          borderRadius: BorderRadius.circular(8.r),
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 17.w),
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.r)),
                            child:
                                quickText('收藏夹($favoriteNumber)', size: 10.sp, color: Color.fromRGBO(102, 102, 102, 1)),
                          ),
                        ),
                      ),
                    ),
                    Expanded(child: SizedBox())
                  ],
                )
              : Container(
                  margin: margin,
                  child: Material(
                    color: Color.fromRGBO(244, 244, 244, 1),
                    borderRadius: BorderRadius.circular(20.r),
                    child: InkWell(
                      onTap: () => bookmarks(context),
                      borderRadius: BorderRadius.circular(8.r),
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 17.w),
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.r)),
                        child: quickText('收藏夹($favoriteNumber)', size: 10.sp, color: Color.fromRGBO(102, 102, 102, 1)),
                      ),
                    ),
                  ),
                );
        }
        return Container();
      },
      future: getInvolveClasses(),
    );
  }
}

/// 收藏夹按钮
// class FavoriteButton extends HookWidget with CommonMixin {
//   final int jobId;
//   final String jobName;
//   EdgeInsets? margin;
//   final bool isRow;
//   FavoriteButton(this.jobId, this.jobName, {this.margin, this.isRow = true, super.key});

//   Future<int> getInvolveClasses() async {
//     print('我的收藏请求数据');
//     try {
//       RestClient _client = await getClient();
//       var result = await _client.getListOfJobFavoriteNumber(jobId);

//       if (result.success && (result.data?.isNotEmpty ?? false)) {
//         return result.data!.map((e) => e.count).reduce((value, element) => value + element);
//       }
//     } catch (e) {
//       print(e);
//     }
//     return 0;
//   }

//   // 收藏夹
//   void bookmarks(BuildContext context) {
//     RouterManager.router.navigateTo(
//       context,
//       RouterManager.jobFavoritePagePath + '?jobId=$jobId&jobName=${Uri.encodeComponent(jobName)}',
//       transition: getTransition(),
//     );
//   }

//   @override
//   Widget build(BuildContext context) {
    
//     var favoriteNumber = useState(0);
//     useEffect(() {
//       getInvolveClasses().then((value) {
//         var favoriteCount = favoriteNumber.value;
//         if (favoriteCount != value) favoriteNumber.value = value;
//       });
//       return () {};
//     }, []);
//     if (favoriteNumber.value <= 0) return Container();
//     margin ??= EdgeInsets.only(top: 15.h);
//     return isRow
//         ? Row(
//             children: [
//               Container(
//                 margin: margin,
//                 child: Material(
//                   color: Color.fromRGBO(244, 244, 244, 1),
//                   borderRadius: BorderRadius.circular(20.r),
//                   child: InkWell(
//                     onTap: () => bookmarks(context),
//                     borderRadius: BorderRadius.circular(8.r),
//                     child: Container(
//                       alignment: Alignment.center,
//                       padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 17.w),
//                       decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.r)),
//                       child: quickText('收藏夹(${favoriteNumber.value})',
//                           size: 10.sp, color: Color.fromRGBO(102, 102, 102, 1)),
//                     ),
//                   ),
//                 ),
//               ),
//               Expanded(child: SizedBox())
//             ],
//           )
//         : Container(
//             margin: margin,
//             child: Material(
//               color: Color.fromRGBO(244, 244, 244, 1),
//               borderRadius: BorderRadius.circular(20.r),
//               child: InkWell(
//                 onTap: () => bookmarks(context),
//                 borderRadius: BorderRadius.circular(8.r),
//                 child: Container(
//                   alignment: Alignment.center,
//                   padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 17.w),
//                   decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.r)),
//                   child:
//                       quickText('收藏夹(${favoriteNumber.value})', size: 10.sp, color: Color.fromRGBO(102, 102, 102, 1)),
//                 ),
//               ),
//             ),
//           );
//   }
// }
