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/test_questions_bo.dart';
import 'package:special_equipment_flutter/model/exam/test_setting_bo.dart';
import 'package:special_equipment_flutter/ui/examine/test/custom/bottom_sheet.dart';
import 'package:special_equipment_flutter/ui/examine/test/custom/choice_item.dart';
import 'package:special_equipment_flutter/widgets/app_bar/custom_app_bar_back.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';

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

  TestPage({super.key});

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

class TestPageState extends State<TestPage> 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;
  DataTest? examineQuestionsBo; //题库总数据
  List<ExamQuestionTestList>? examQuestionList = []; //题库列表数据
  List<ExamQuestionTestList>? examQuestionDList = []; //选择题
  List<ExamQuestionTestList>? examQuestionPList = []; //判断题
  TestSubmitBo? mTestSubmitBo;
  var positionType = '';

  @override
  void initState() {
    super.initState();
    mTestSubmitBo = widget.arguments['mTestSubmitBo'];
    positionType = widget.arguments['positionType'];

    getQuestionsData();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..forward();
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.bounceOut,
    );
  }

  ///获取考核试卷
  void getQuestionsData() {
    HttpUtils.getTestQuestions(
            context, mTestSubmitBo!.mEquiList!.id, positionType, "0", "0", "0")
        .then((value) {
      TestQuestionsBo 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]);
            }
          }
        });
      }
    });
  }

  @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.white,
          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<ExamQuestionTestList>? 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: bgColors(examQuestionList[index]),

                    ///设置圆圈为蓝色
                    border:
                        Border.all(color: bgColors2(examQuestionList[index])!),
                    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)),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Color? bgColors2(ExamQuestionTestList examQuestionTestList) {
    if (examQuestionTestList.result != null) {
      ///回答的和答案相同
      if (examQuestionTestList.result == examQuestionTestList.answer) {
        return ColorConst.themeBgColor;
      } else {
        return ColorConst.red1BgColor;
      }
    } else {
      ///如果result为空的话，说明还没有选择
      return ColorConst.greyD2Color;
    }
  }

  Color? bgColors(ExamQuestionTestList examQuestionTestList) {
    if (examQuestionTestList.result != null) {
      ///回答的和答案相同
      if (examQuestionTestList.result == examQuestionTestList.answer) {
        return ColorConst.themeBgColor;
      } else {
        return ColorConst.red1BgColor;
      }
    } else {
      ///如果result为空的话，说明还没有选择
      return Colors.white;
    }
  }

  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];
                  return InkWell(
                    splashColor: questions.result == null
                        ? ColorConst.themeBgColor
                        : Colors.transparent,
                    onTap: () {
                      ///如果已选择，禁止重新选择
                      if (questions.result != null) {
                        return;
                      }

                      setState(() {
                        //将其他选项全部置为false
                        questions.examQuestionOptionList!
                            .forEach((element) => element.flag = '-1');
                        // //将当前选项置为true
                        // options.isSelected = true;
                        if (questions.answer == options.options) {
                          options.flag = '1';
                        } else {
                          options.flag = '0';
                        }
                        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),
                  );
                },
              ),

              Visibility(
                visible:
                    examQuestionList![index1].result != null ? true : false,
                child: Container(
                  margin: const EdgeInsets.only(
                      top: 20, bottom: 0, left: 15, right: 15),
                  padding: const EdgeInsets.only(
                      left: 20, right: 20, top: 10, bottom: 10),
                  width: double.infinity,
                  decoration: const BoxDecoration(
                    color: ColorConst.greyF2Color,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                  child: Row(
                    children: [
                      const Text(
                        "答案  ",
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        "${examQuestionList![index1].answer}",
                        style: const TextStyle(
                            color: ColorConst.greenColor, fontSize: 18),
                      )
                    ],
                  ),
                ),
              )
            ],
          );
        },
        onPageChanged: (int index) {
          setState(() {
            _currentPage = index;
          });
        },
      ),
    );
  }

  ///题干
  Container questionStems(int index, ExamQuestionTestList 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)),
        ],
      ),
    );
  }

  ///交卷
  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: () {
              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();
                      // HttpUtils.getTestSubmit(context, examineQuestionsBo)
                      //     .then((value) {
                      //   ExamResultBo examResultBo = value;
                      //   if (mounted) {
                      //     setState(() {
                      //       var testResultDataBo = examResultBo.data;
                      //       ToastUtils.showCenter('试卷提交完成');
                      //       Get.offNamed(RouteString.TEST_RESULT_PAGE,
                      //           arguments: {
                      //             'testResultDataBo': testResultDataBo
                      //           })?.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),
            )));
  }
}
