/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 2022-07-12 16:29:30
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-09-28 13:48:52
 * @FilePath: \marking_app\lib\components\TestPaperItem.dart
 * @Description: 阅卷任务ITEM
 */
import 'package:achievement_view/achievement_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.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_structure_result.dart';
import 'package:marking_app/common/model/enum/marking_list_type.dart';
import 'package:marking_app/common/model/enum/subject.dart';
import 'package:marking_app/common/model/marking/current_review_task.dart';
import 'package:marking_app/common/model/marking/marking_item.dart';
import 'package:marking_app/provider/review_provider.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/percent_indicator.dart';

class TestPaperItem extends ConsumerWidget with CommonMixin {
  final MarkingItem markingItem;
  final bool isHomeworkCorrection;
  final VoidCallback? call;
  final MarkingListType? markingtype;
  const TestPaperItem(
      {required this.markingItem, this.markingtype, this.isHomeworkCorrection = false, this.call, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    double indent = 6.w; // 缩进宽度.
    switch (markingtype) {
      case MarkingListType.EXCEPTIONAL:
      case MarkingListType.ARBITRATE:
        indent += 20.w + 8.w;
        break;
      case MarkingListType.NORMAL:
        indent += 36.w + 8.w;
        break;
      default:
        indent = 0;
    }

    final textPainter = TextPainter(
      text: TextSpan(text: " ", style: TextStyle(fontSize: 18.sp)),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();
    final spaceWidth = textPainter.width;

    String spaceText = '';
    List.generate((indent / spaceWidth).floor(), (e) => null).forEach((element) {
      spaceText += ' ';
    });

    return Container(
      margin: EdgeInsets.only(top: 12.h, left: 14.w, right: 14.w),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
      constraints: BoxConstraints(
        minHeight: 120.h,
        maxHeight: 130.h,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.w)),
        boxShadow: [
          BoxShadow(
            color: const Color.fromRGBO(46, 91, 255, 0.1),
            offset: Offset(0, -0.4.h), //阴影y轴偏移量
            blurRadius: 10, //阴影模糊程度
            spreadRadius: 6, //阴影扩散程度
          )
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Stack(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // SizedBox(width: indent),
                  // if (isHomeworkCorrection)
                  //   Container(
                  //     padding: EdgeInsets.all(2.w),
                  //     margin: EdgeInsets.only(right: 8.w),
                  //     child: Icon(Icons.menu_book_rounded, size: 18.sp),
                  //   ),
                  Expanded(
                    child: Text(
                      spaceText + markingItem.examName,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w400,
                        color: const Color.fromRGBO(45, 56, 76, 1),
                      ),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  if (markingtype == MarkingListType.EXCEPTIONAL)
                    Container(
                      width: 20.w,
                      padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 2.h),
                      margin: EdgeInsets.only(right: 8.w),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.only(topLeft: Radius.circular(6.r), bottomRight: Radius.circular(6.r)),
                        color: const Color.fromRGBO(245, 108, 108, 0.236),
                      ),
                      child: Text(
                        '异',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: const Color.fromRGBO(215, 74, 74, 1),
                        ),
                      ),
                    ),
                  if (markingtype == MarkingListType.ARBITRATE)
                    Container(
                      width: 20.w,
                      padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 2.h),
                      margin: EdgeInsets.only(right: 8.w),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.only(topLeft: Radius.circular(6.r), bottomRight: Radius.circular(6.r)),
                        color: const Color.fromRGBO(4, 201, 208, 0.10),
                      ),
                      child: Text(
                        '仲',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: const Color.fromRGBO(4, 201, 208, 1),
                        ),
                      ),
                    ),
                  if (markingtype == MarkingListType.NORMAL)
                    Container(
                      width: 36.w,
                      padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 2.h),
                      margin: EdgeInsets.only(right: 8.w),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.only(topLeft: Radius.circular(6.r), bottomRight: Radius.circular(6.r)),
                        color: const Color.fromRGBO(231, 236, 255, 1),
                      ),
                      child: Text(
                        '月考',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: const Color.fromRGBO(46, 91, 255, 1),
                        ),
                      ),
                    ),
                ],
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    getSubjectEnumName(markingItem.subjectId),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                      color: const Color.fromRGBO(80, 87, 103, 1),
                    ),
                  ),
                  Container(
                    width: 1.w,
                    height: 10.sp,
                    color: const Color.fromRGBO(80, 87, 103, 1),
                    margin: EdgeInsets.symmetric(horizontal: 10.w),
                  ),
                  if (markingtype == MarkingListType.NORMAL || isHomeworkCorrection)
                    Text(
                      '题量：${markingItem.totalCount}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w400,
                        color: const Color.fromRGBO(80, 87, 103, 1),
                      ),
                    )
                  else if (markingtype == MarkingListType.EXCEPTIONAL)
                    Container(
                      margin: EdgeInsets.only(right: 4.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.warning_amber_rounded,
                            color: const Color.fromRGBO(215, 74, 74, 1),
                            size: 15.sp,
                          ),
                          SizedBox(width: 2.w),
                          if ((markingItem.totalCount - markingItem.finishCount) > 0)
                            quickText(
                              '${markingItem.totalCount - markingItem.finishCount}个异常待处理',
                              color: Colors.red,
                              size: 11.sp,
                            )
                          else
                            quickText('暂无异常', color: Colors.grey, size: 11.sp)
                        ],
                      ),
                    )
                  else if (markingtype == MarkingListType.ARBITRATE)
                    Container(
                      margin: EdgeInsets.only(right: 4.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.edit_square,
                            color: const Color.fromRGBO(4, 201, 208, 1),
                            size: 15.sp,
                          ),
                          SizedBox(width: 2.w),
                          if ((markingItem.totalCount - markingItem.finishCount) > 0)
                            quickText(
                              '${markingItem.totalCount - markingItem.finishCount}个仲裁待处理',
                              color: const Color.fromRGBO(4, 201, 208, 1),
                              size: 11.sp,
                            )
                          else
                            quickText('暂无仲裁', color: Colors.grey, size: 11.sp)
                        ],
                      ),
                    )
                ],
              ),
              Expanded(child: SizedBox()),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: EdgeInsets.only(right: 4.w),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          '${markingItem.finishCount}',
                          style: TextStyle(
                              color: markingItem.isFinish && isHomeworkCorrection
                                  ? Colors.green
                                  : Theme.of(context).primaryColor,
                              fontSize: 12.sp),
                        ),
                        Text(
                          '/',
                          style: TextStyle(color: const Color.fromRGBO(148, 163, 182, 1), fontSize: 12.sp),
                        ),
                        Text(
                          '${markingItem.totalCount}',
                          style: TextStyle(color: Color.fromRGBO(148, 163, 182, 1), fontSize: 12.sp),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 100.w,
                    child: LinearPercentIndicator(
                      padding: EdgeInsets.zero,
                      animation: true,
                      lineHeight: 8.h,
                      animationDuration: 2500,
                      percent: markingItem.completionRate,
                      center: Text(
                        '${markingItem.completionRateStr}%',
                        style: TextStyle(color: Colors.white, fontSize: 8.sp),
                      ),
                      // linearStrokeCap: LinearStrokeCap.butt,
                      progressColor:
                          markingItem.isFinish && isHomeworkCorrection ? Colors.green : Theme.of(context).primaryColor,
                      backgroundColor: const Color.fromRGBO(219, 224, 243, 1),
                      barRadius: Radius.circular(10.r),
                    ),
                  ),
                ],
              ),
            ],
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                if (markingItem.isFinish)
                  Container(
                    margin: EdgeInsets.only(left: 7.w),
                    child: MaterialButton(
                      color: const Color.fromRGBO(245, 246, 251, 1),
                      disabledColor: const Color.fromRGBO(245, 246, 251, 1),
                      textColor: const Color.fromRGBO(80, 87, 103, 1),
                      minWidth: 60.w,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(6.w),
                        ),
                      ),
                      onPressed: () {
                        // goToReviewHomework(markingItem: markingItem, ref: ref, context: context, call: () => call!());
                      },
                      child: Text(
                        '已完成',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: const Color.fromRGBO(148, 163, 182, 1),
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                if (false && !markingItem.isFinish && !isHomeworkCorrection)
                  MaterialButton(
                    color: const Color.fromRGBO(245, 246, 251, 1),
                    disabledColor: const Color.fromRGBO(245, 246, 251, 1),
                    minWidth: 60.w,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(6.w)),
                    ),
                    onPressed: () {
                      int examSubjectId = markingItem.examSubjectId;
                      RouterManager.router.navigateTo(
                        context,
                        '${RouterManager.markingProgressPath}?examSubjectId=$examSubjectId&name=${Uri.encodeComponent(markingItem.examName)}',
                        transition: getTransition(),
                      );
                    },
                    child: Text(
                      '进度',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: const Color.fromRGBO(80, 87, 103, 1),
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                /** 异常和仲裁没有回评 注释回评
                 if (markingtype == MarkingListType.NORMAL && !markingItem.isFinish && markingItem.finishCount > 0)
                  Container(
                    margin: EdgeInsets.only(left: 7.w),
                    child: MaterialButton(
                      color: const Color.fromRGBO(245, 246, 251, 1),
                      disabledColor: const Color.fromRGBO(245, 246, 251, 1),
                      textColor: const Color.fromRGBO(80, 87, 103, 1),
                      minWidth: 60.w,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(6.w))),
                      onPressed: () {
                        RouterManager.router.navigateTo(
                          context,
                          '${isHomeworkCorrection ? RouterManager.markingJobReviewPath : RouterManager.markingReviewPath}?markingtype=${markingtype?.index}&markingUserId=${markingItem.markingUserId}&examSubjectId=${markingItem.examSubjectId}&examName=${Uri.encodeComponent(markingItem.examName)}',
                          transition: getTransition(),
                        );
                      },
                      child: Text(
                        '回评',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: const Color.fromRGBO(80, 87, 103, 1),
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                 */
                if (!markingItem.isFinish)
                  if ([MarkingListType.EXCEPTIONAL, MarkingListType.ARBITRATE].contains(markingtype))
                    Container(
                      margin: EdgeInsets.only(left: 7.w),
                      child: MaterialButton(
                        color: const Color.fromRGBO(54, 86, 255, 0.99),
                        disabledColor: const Color.fromRGBO(54, 86, 255, 0.99),
                        onPressed: markingItem.isFinish
                            ? null
                            : () {
                                if (markingItem.finishCount == 0 && markingItem.totalCount == 0) {
                                  return AchievementView(
                                    elevation: 0.5,
                                    duration: Duration(seconds: 1),
                                    title: "提示",
                                    subTitle: "暂时没有任务，休息一会吧",
                                    color: Theme.of(context).primaryColor,
                                  ).show(context);
                                }
                                goToReviewTestPaper(
                                  markingtype: markingtype!,
                                  markingItem: markingItem,
                                  ref: ref,
                                  context: context,
                                  call: call,
                                );
                              },
                        minWidth: 60.w,
                        shape: RoundedRectangleBorder(
                          //边框颜色
                          // side: const  BorderSide(
                          //   color: Colors.deepPurple,
                          //   width: 1,
                          // ),
                          //边框圆角
                          borderRadius: BorderRadius.all(Radius.circular(6.w)),
                        ),
                        padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 4.h),
                        child: Text(
                          '处 理',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    )
                  else
                    Container(
                      margin: EdgeInsets.only(left: 7.w),
                      child: MaterialButton(
                        color: const Color.fromRGBO(54, 86, 255, 0.99),
                        disabledColor: const Color.fromRGBO(54, 86, 255, 0.99),
                        onPressed: markingItem.isFinish
                            ? null
                            : () {
                                if (markingItem.finishCount == 0 && markingItem.totalCount == 0) {
                                  return AchievementView(
                                    elevation: 0.5,
                                    duration: Duration(seconds: 1),
                                    title: "提示",
                                    subTitle: "暂时没有任务，休息一会吧",
                                    color: Theme.of(context).primaryColor,
                                  ).show(context);
                                }
                                isHomeworkCorrection
                                    // ? goToReviewHomework(
                                    //     markingItem: markingItem, ref: ref, context: context, call: () => call!())
                                    ? () => {}
                                    : goToReviewTestPaper(
                                        markingtype: markingtype!,
                                        markingItem: markingItem,
                                        ref: ref,
                                        context: context,
                                        call: call,
                                      );
                              },
                        minWidth: 60.w,
                        shape: RoundedRectangleBorder(
                          //边框颜色
                          // side: const  BorderSide(
                          //   color: Colors.deepPurple,
                          //   width: 1,
                          // ),
                          //边框圆角
                          borderRadius: BorderRadius.all(Radius.circular(6.w)),
                        ),
                        child: Text(
                          isHomeworkCorrection ? '批阅' : '阅卷',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 结束阅卷任务
  Future<void> toTaskEnd(BuildContext context, WidgetRef ref, String markingUserId) async {
    RestClient client = await getClient();
    BaseStructureResult<bool?> result = await client.endMarkingTask(markingUserId);
    if (result.code == RequestConfig.successCode && result.data == null ? false : result.data!) {
      ref
          .read(currentTaskIdProvider.notifier)
          .setDoTaskEntity(CurrentReviewTask(taskId: markingItem.markingUserId, refresh: true));
    } else {
      ToastUtils.getFluttertoast(context: context, msg: '提交失败');
    }
  }

  // 批阅作业
  // Future<void> goToReviewHomework({
  //   required MarkingItem markingItem,
  //   required WidgetRef ref,
  //   required BuildContext context,
  //   required VoidCallback call,
  // }) async {
  //   int taskId = markingItem.markingUserId;
  //   toPrint(val: '批阅作业.........');
  //   // ref.read(currentTaskIdProvider.notifier).setDoTaskEntity(CurrentReviewTask(taskId: taskId));
  //   // DetailId 回评需要传DetailId，正常阅卷不需要；PageOper(0：下一题，1：上一题，2：当前题) 回评需要传2 ；IsReview 是否会评 0否 1是
  //   RouterManager.router
  //       .navigateTo(context, '${RouterManager.markingHomeworkDoPath}?taskId=$taskId', transition: getTransition())
  //       .then((value) {
  //     call();
  //   });
  // }

  // 批阅试卷
  Future<void> goToReviewTestPaper({
    required MarkingListType markingtype,
    required MarkingItem markingItem,
    required WidgetRef ref,
    required BuildContext context,
    VoidCallback? call,
  }) async {
    int taskId = markingItem.markingUserId;
    int examSubjectId = markingItem.examSubjectId;
    ref.read(currentTaskIdProvider.notifier).setDoTaskEntity(CurrentReviewTask(taskId: taskId));

    // DetailId 回评需要传DetailId，正常阅卷不需要；PageOper(0：下一题，1：上一题，2：当前题) 回评需要传2 ；IsReview 是否会评 0否 1是
    return RouterManager.router
        .navigateTo(
      context,
      '${RouterManager.markingDoPath}?markingtype=${markingtype.index}&markingUserId=$taskId&examSubjectId=$examSubjectId&detailId=${null}&pageOper=${null}',
      transition: getTransition(),
    )
        .then((value) {
      if (value == true && call != null) call();
    });
  }
}
