import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/exam/exam_result_bo.dart';
import 'package:special_equipment_flutter/model/exam/examine_person_bo.dart';
import 'package:special_equipment_flutter/model/exam/examine_questions_bo.dart';
import 'package:special_equipment_flutter/model/exam/show_answer_bo.dart';
import 'package:special_equipment_flutter/ui/examine/exam/custom/choice_item.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/app_bar/custom_app_bar_back.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';

import '../../../common/route_string.dart';
import 'custom/bottom_sheet.dart';

///考核答题页面
class ExamPage extends StatefulWidget {
  var arguments = Get.arguments;

  ExamPage({super.key});

  @override
  createState() {
    return ExamPageState();
  }
}

class ExamPageState extends State<ExamPage> with TickerProviderStateMixin {
  final GlobalKey<DragBottomSheetWidgetState> bottomSheetKey =
      GlobalKey<DragBottomSheetWidgetState>();
  bool isExpand = false;
  final _pageController = PageController(initialPage: 0);
  late int _currentPage = 0;

  PanelController? controller = PanelController();
  late final AnimationController _controller;
  late final Animation<double> _animation;
  Data? examineQuestionsBo; //题库总数据
  List<ExamQuestionList>? examQuestionList = []; //题库列表数据
  List<ExamQuestionList>? examQuestionDList = []; //选择题
  List<ExamQuestionList>? examQuestionPList = []; //判断题
  DataExaminePerson? mExaminePersonBo;
  String? showAnswerData = '2';

  @override
  void initState() {
    super.initState();
    mExaminePersonBo = widget.arguments['mExaminePersonBo'];
    getShowAnswer();
    getQuestionsData();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..forward();
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.bounceOut,
    );
  }

  ///获取考核试卷
  void getQuestionsData() {
    // HttpUtils.getExamineQuestions(context, '1', '2024-05-17',
    //     '779d6023cd4148b49288eb3e3616a7e3', '2', 10, 10)
    HttpUtils.getExamineQuestions(
            context,
            mExaminePersonBo!.inspectors!.id,
            mExaminePersonBo!.examDate,
            mExaminePersonBo!.type!.id,
            mExaminePersonBo!.xzNum! + mExaminePersonBo!.pdNum!,
            mExaminePersonBo!.xzNum,
            mExaminePersonBo!.pdNum,
            mExaminePersonBo!.id)
        .then((value) {
      ExamineQuestionsBo listBo = value;
      if (mounted) {
        setState(() {
          examineQuestionsBo = listBo.data;
          examQuestionList = examineQuestionsBo!.examQuestionList;

          ///答题卡标题、序号
          for (var i = 0; i < examQuestionList!.length; i++) {
            ///单选
            if (examQuestionList![i].questionType == '1') {
              examQuestionDList!.add(examQuestionList![i]);
            } else {
              examQuestionPList!.add(examQuestionList![i]);
            }
          }
        });
      }
    });
  }

  ///考核 是否显示答案
  void getShowAnswer() {
    HttpUtils.getShowAnswer(context).then((value) {
      ShowAnswerBo mShowAnswerBo = value;
      if (mounted) {
        setState(() {
          showAnswerData = mShowAnswerBo.data;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.dialog(AlertDialog(
          title: const Text("温馨提示"),
          content: const Text("您确定要结束当前考试？"),
          actionsPadding:
              const EdgeInsets.only(left: 0, top: 0, bottom: 10, right: 20),
          contentPadding:
              const EdgeInsets.only(left: 20, top: 0, bottom: 10, right: 20),
          titlePadding:
              const EdgeInsets.only(left: 20, top: 20, bottom: 10, right: 20),
          shape: const RoundedRectangleBorder(
              // 这里设置shape属性
              borderRadius: BorderRadius.all(Radius.circular(10.0))),
          actions: <Widget>[
            TextButton(
              child: const Text("取消", style: TextStyle(fontSize: 16)),
              onPressed: () {
                Get.back();
              },
            ),
            TextButton(
              child: const Text("确定", style: TextStyle(fontSize: 16)),
              onPressed: () {
                Get.back();
                Get.back();
              },
            ),
          ],
        ));
        return true; // 控制是否可以侧滑返回，true为允许，false为不允许
      },
      child: Scaffold(
          backgroundColor: Colors.grey[100],
          appBar: AppBarCustom(
            leading: IconButton(
              iconSize: 20,
              icon: const Icon(Icons.arrow_back_ios),
              color: ColorConst.whiteColor,
              onPressed: () {
                Get.dialog(AlertDialog(
                  title: const Text("温馨提示"),
                  content: const Text("您确定要结束当前考试？"),
                  actionsPadding: const EdgeInsets.only(
                      left: 0, top: 0, bottom: 10, right: 20),
                  contentPadding: const EdgeInsets.only(
                      left: 20, top: 0, bottom: 10, right: 20),
                  titlePadding: const EdgeInsets.only(
                      left: 20, top: 20, bottom: 10, right: 20),
                  shape: const RoundedRectangleBorder(
                      // 这里设置shape属性
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  actions: <Widget>[
                    TextButton(
                      child: const Text("取消", style: TextStyle(fontSize: 16)),
                      onPressed: () {
                        Get.back();
                      },
                    ),
                    TextButton(
                      child: const Text("确定", style: TextStyle(fontSize: 16)),
                      onPressed: () {
                        Get.back();
                        Get.back();
                      },
                    ),
                  ],
                ));
              },

              ///这里设置了按钮的内边距为零，可以消除默认的16像素间距
              padding: EdgeInsets.zero,
            ),
            text: '考核',
            height: 50,
          ),

          ///答题卡抽屉
          body: SlidingUpPanel(
            backdropEnabled: true,
            controller: controller,
            minHeight: 50,
            maxHeight: 510,

            ///答题卡区
            panel: Container(
              color: Colors.grey[200],
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        InkWell(
                          onTap: () {
                            setState(() {
                              if (controller!.isPanelClosed) {
                                controller!.open();
                              } else {
                                controller!.close();
                              }
                            });
                          },
                          child: Container(
                            padding: const EdgeInsets.only(top: 7, bottom: 6),
                            // color: Colors.grey[300],
                            child: Stack(
                              alignment: Alignment.centerRight,
                              children: [
                                Column(
                                  children: [
                                    Image.asset(
                                      'assets/examine/answer_sheet_black_icon.png',
                                      width: 20,
                                      height: 20,
                                    ),
                                    Container(
                                        margin: const EdgeInsets.only(top: 2)),
                                    const Text(
                                      '答题卡',
                                      style: TextStyle(fontSize: 12),
                                    )
                                  ],
                                ),
                                Container(
                                  margin: const EdgeInsets.only(right: 15),
                                  child: Text.rich(
                                      softWrap: true,
                                      TextSpan(children: [
                                        TextSpan(
                                            text: "${_currentPage + 1}",
                                            style: const TextStyle(
                                                fontSize: 20,
                                                color: ColorConst.blueColor,
                                                fontWeight: FontWeight.bold)),
                                        TextSpan(
                                            text:
                                                " /${examQuestionList!.length}",
                                            style: const TextStyle(
                                                fontSize: 15,
                                                color: Colors.black87)),
                                      ])),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          height: 380,
                          margin: const EdgeInsets.only(
                              top: 0, left: 10, right: 10),
                          padding: const EdgeInsets.all(10),
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                          ),
                          child: CustomScrollView(
                            primary: false,
                            shrinkWrap: true,
                            slivers: <Widget>[
                              SliverToBoxAdapter(
                                  child: Column(
                                children: [
                                  if (examQuestionDList!.isNotEmpty) ...{
                                    buildSliverToBoxAdapter('选择题'),
                                    buildAnswerSheetList(examQuestionDList),
                                  },
                                  if (examQuestionPList!.isNotEmpty) ...{
                                    buildSliverToBoxAdapter('判断题'),
                                    buildAnswerSheetList(examQuestionPList),
                                  }
                                ],
                              ))
                            ],
                          ),
                        ),
                      ]),
                  buildSubmit()
                ],
              ),
            ),

            ///内容区
            body: Column(children: [buildExpanded()]),
          )),
    );
  }

  Container buildSliverToBoxAdapter(var text) {
    return Container(
      padding: const EdgeInsets.only(left: 0, top: 5, bottom: 0),
      alignment: Alignment.centerLeft,
      child: Text(
        text,
        style: const TextStyle(fontSize: 16, color: Colors.black),
      ),
    );
  }

  ///答题卡
  Widget buildAnswerSheetList(List<ExamQuestionList>? examQuestionList) {
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.only(left: 10, top: 10, bottom: 10),
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 6,
        crossAxisSpacing: 13,
        mainAxisSpacing: 10,
        childAspectRatio: 1, //子项的宽高比，值越大高度越高
      ),
      itemCount: examQuestionList!.length,
      itemBuilder: (context, index) {
        return AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Transform.scale(
              scale: _animation.value,
              child: InkWell(
                onTap: () {
                  _pageController.jumpToPage(examQuestionList[index].sort! - 1);
                  controller!.close();
                },
                child: Container(
                  height: 20,
                  width: 20,
                  decoration: BoxDecoration(
                    ///设置当前选中选项圆圈背景为蓝色、未选中选项圆圈背景为白色
                    color: examQuestionList[index].result != null
                        ? ColorConst.themeBgColor[700]
                        : Colors.white,

                    ///设置圆圈为蓝色
                    border: Border.all(
                        color: examQuestionList[index].result != null
                            ? ColorConst.themeBgColor
                            : ColorConst.greyD2Color),
                    borderRadius: const BorderRadius.all(Radius.circular(90)),
                  ),
                  child: Center(
                    child: Text(examQuestionList[index].sort!.toString(),
                        style: TextStyle(
                            color: examQuestionList[index].result != null
                                ? ColorConst.whiteColor
                                : ColorConst.dark9Color,
                            fontSize: 16.0)),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Expanded buildExpanded() {
    return Expanded(
      child: PageView.builder(
        controller: _pageController,
        itemCount: examQuestionList?.length,
        itemBuilder: (BuildContext context, int index1) {
          var questions = examQuestionList![index1];
          return Column(
            textDirection: TextDirection.ltr,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ///题干
              questionStems(index1, questions),

              ///试题图片
              // if (!StringUtils.strIsEmpty("${questions.image}")) ...[
              //   questionImage(context, questions)
              // ],

//              Visibility(child: questionImage(context, questions),visible:!StringUtils.strIsEmpty("${questions.image}")),

              // SingleOption(
              //   question: questions,
              //   pageController: _pageController,
              //   index: index1,
              // ),

              ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: questions.examQuestionOptionList?.length,
                itemBuilder: (BuildContext context, int index) {
                  var options = questions.examQuestionOptionList![index];

                  ///showAnswerData==1 显示答案
                  if (showAnswerData == '1') {
                    if (questions.answer == options.options) {
                      options.isAcquiesceSelected = true;
                    }
                  }
                  return InkWell(
                    splashColor: ColorConst.themeBgColor,
                    onTap: () {
                      setState(() {
                        //将其他选项全部置为false
                        questions.examQuestionOptionList!
                            .forEach((element) => element.isSelected = false);
                        //将当前选项置为true
                        options.isSelected = true;
                        questions.result = options.options;

                        if (examQuestionList?.length == index1 + 1) {
                          controller!.open();
                        } else {
                          //延时1秒
                          Future.delayed(const Duration(milliseconds: 500), () {
                            _pageController.jumpToPage(index1 + 1);
                          });
                        }
                      });
                    },
                    child: ChoiceItem(option: options),
                  );
                },
              ),
            ],
          );
        },
        onPageChanged: (int index) {
          setState(() {
            _currentPage = index;
          });
        },
      ),
    );
  }

  ///题干
  Container questionStems(int index, ExamQuestionList questions) {
    return Container(
      //设置内边距
      padding: const EdgeInsets.only(top: 20, bottom: 10, left: 10, right: 10),
      child: Stack(
        children: [
          Container(
            width: 35,
            height: 20,
            margin: const EdgeInsets.fromLTRB(0, 2, 0, 0),
            alignment: Alignment.center,
            decoration: const BoxDecoration(
                color: ColorConst.themeBgColor,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(8),
                    topRight: Radius.circular(2),
                    bottomLeft: Radius.circular(2),
                    bottomRight: Radius.circular(8))),
            child: Text(
              questions.questionType == '1' ? '单选' : '判断',
              style: const TextStyle(fontSize: 12, color: Colors.white),
            ),
          ),
          Text("\t\t\t\t\t\t\t\t\t\t${index + 1}、${questions.content}",
              style: const TextStyle(
                  fontSize: 16, fontWeight: FontWeight.bold, height: 1.5)),
        ],
      ),
    );
  }

  int noReplyNum = 0;

  ///交卷
  Container buildSubmit() {
    return Container(
        margin: const EdgeInsets.only(top: 10, bottom: 0),
        padding:
            const EdgeInsets.only(left: 20, right: 20, top: 15, bottom: 15),
        width: double.infinity,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: GradientButton(
            tapCallback: () {
              noReplyNum = 0;
              for (var i = 0; i < examQuestionList!.length; i++) {
                if (examQuestionList![i].result == null) {
                  noReplyNum++;
                }
              }
              Get.dialog(AlertDialog(
                title: const Text("温馨提示"),
                content: noReplyNum != 0
                    ? /*Text("您还有 ${noReplyNum.toString()} 道题未作答\n您确定要提交考核试卷吗？")*/
                    Text.rich(
                        softWrap: true,
                        TextSpan(children: [
                          const TextSpan(
                            text: '您还有 ',
                            style: TextStyle(color: Colors.black),
                          ),
                          TextSpan(
                            text: noReplyNum.toString(),
                            style: const TextStyle(
                                color: Colors.red,
                                fontWeight: FontWeight.bold,
                                fontSize: 25),
                          ),
                          const TextSpan(
                            text: ' 道题未作答\n您确定要提交考核试卷吗？',
                            style: TextStyle(color: Colors.black),
                          ),
                        ]))
                    : const Text.rich(
                        softWrap: true,
                        TextSpan(children: [
                          TextSpan(
                            text: '试题已全部作答完成\n',
                            style: TextStyle(
                                color: Colors.green,
                                fontWeight: FontWeight.bold,
                                fontSize: 18),
                          ),
                          TextSpan(
                            text: '您确定要提交考核试卷吗？',
                            style: TextStyle(color: Colors.black),
                          ),
                        ])),
                actionsPadding: const EdgeInsets.only(
                    left: 0, top: 0, bottom: 10, right: 20),
                contentPadding: const EdgeInsets.only(
                    left: 20, top: 0, bottom: 10, right: 20),
                titlePadding: const EdgeInsets.only(
                    left: 20, top: 20, bottom: 10, right: 20),
                shape: const RoundedRectangleBorder(
                    // 这里设置shape属性
                    borderRadius: BorderRadius.all(Radius.circular(10.0))),
                actions: <Widget>[
                  TextButton(
                    child: const Text("取消", style: TextStyle(fontSize: 16)),
                    onPressed: () {
                      Get.back();
                    },
                  ),
                  TextButton(
                    child: const Text("确定", style: TextStyle(fontSize: 16)),
                    onPressed: () {
                      //关闭弹窗
                      Get.back();
                      HttpUtils.getExamSubmit(context, examineQuestionsBo)
                          .then((value) {
                        ExamResultBo examResultBo = value;
                        if (mounted) {
                          setState(() {
                            var examResultDataBo = examResultBo.data;
                            ToastUtils.showCenter('试卷提交完成');
                            Get.offNamed(RouteString.EXAM_RESULT_PAGE,
                                arguments: {
                                  'examResultDataBo': examResultDataBo
                                })?.then((value) {
                              if (value != null && value) {
                                //关闭当前页面
                                Get.back();
                              }
                            });
                          });
                        }
                      });
                    },
                  ),
                ],
              ));
            },
            width: 300,
            height: 40,
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(20),
                bottomRight: Radius.circular(10)),
            disable: false,
            colors: const [ColorConst.blueColor, ColorConst.blue1Color],
            child: const Text(
              "交卷",
              style: TextStyle(fontSize: 14, color: ColorConst.whiteColor),
            )));
  }
}
