import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/exam/eq_question_bo.dart';
import 'package:special_equipment_flutter/model/exam/equipment_list_bo.dart';
import 'package:special_equipment_flutter/model/exam/test_setting_bo.dart';
import 'package:special_equipment_flutter/model/role_bo.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';
import 'package:special_equipment_flutter/widgets/custom_textfield.dart';
import 'package:special_equipment_flutter/widgets/tip.dart';

///测试练习设置
class TestSettingPage extends StatefulWidget {
  TestSettingPage({super.key});

  var arguments = Get.arguments;

  @override
  State<TestSettingPage> createState() => _TestSettingPageState();
}

class _TestSettingPageState extends State<TestSettingPage> {
  TextEditingController? equipmentText = TextEditingController();
  FocusNode? equipmentFocusNode = FocusNode();
  TextEditingController? roleText = TextEditingController();
  FocusNode? roleFocusNode = FocusNode();
  TextEditingController? singleText = TextEditingController();
  FocusNode? singleZJFocusNode = FocusNode();
  TextEditingController? judgmentText = TextEditingController();
  FocusNode? judgmentZJFocusNode = FocusNode();
  int allQuestions = 0;
  EquiList? mEquiList;
  DataEq? mDataEq;
  var unitType = '1';

  List<UserData>? roleUserLists = [];
  var roleId = '', roleName = '';

  @override
  void initState() {
    super.initState();
    // getFindQuestionNum();
    // getFindEqQuestionNum(true);
    unitType = widget.arguments['unitType'];
    String roles = widget.arguments['roles'];

    var roleLists = roles.split(',');
    if (roleLists.contains('主要负责人')) {
      roleLists.remove('主要负责人');
    }
    for (var name in roleLists) {
      UserData mUserData = UserData();
      mUserData.roleName = name;

      ///使用单位
      if (unitType == '1') {
        if (name == '安全员') {
          mUserData.roleId = '2';
        }
        if (name == '安全总监') {
          mUserData.roleId = '1';
        }
      }

      ///生产单位
      if (unitType == '2') {
        if (name == '质量安全员') {
          mUserData.roleId = '2';
        }
        if (name == '质量安全总监') {
          mUserData.roleId = '1';
        }
      }
      roleUserLists!.add(mUserData);
    }

    if (roleUserLists!.length == 1) {
      roleId = roleUserLists![0].roleId!;
      // roleName = roleUserLists![0].roleName!;
      roleText!.text = roleUserLists![0].roleName!;
    }
    getEquipmentList();
  }

  ///获取设备类型
  void getEquipmentList() {
    HttpUtils.getEquipmentList(context, StorageUtil.getInstance().getOfficeId())
        .then((value) {
      EquipmentListBo listBo = value;
      if (mounted) {
        setState(() {
          try {
            mEquiList = listBo.list![0];
            equipmentText!.text = mEquiList!.name!;
          } catch (e) {}
        });
      }
    });
  }

  ///获取题数
  // void getFindQuestionNum() {
  //   HttpUtils.getFindQuestionNum(context).then((value) {
  //     FindQuestionNum listBo = value;
  //     if (mounted) {
  //       setState(() {
  //         DataNum dataNum = listBo.data!;
  //         singleText!.text = dataNum.aqyDx!.toString();
  //         judgmentText!.text = dataNum.aqyPd!.toString();
  //         allQuestions = dataNum.aqyDx! + dataNum.aqyPd!;
  //       });
  //     }
  //   });
  // }

  ///根据设备类型获取总题数
  // void getFindEqQuestionNum(isFirst) {
  //   HttpUtils.getFindEqQuestionNum(context, mEquiList!.id!).then((value) {
  //     EqQuestionBo listBo = value;
  //     if (mounted) {
  //       setState(() {
  //         mDataEq = listBo.data!;
  //         if (isFirst) {
  //           singleText!.text = mDataEq!.dxNum!.toString();
  //           judgmentText!.text = mDataEq!.pdNum!.toString();
  //           allQuestions = mDataEq!.dxNum! + mDataEq!.pdNum!;
  //         } else {
  //           if (int.parse(singleText!.text) > mDataEq!.dxNum!) {
  //             singleText!.text = mDataEq!.dxNum!.toString();
  //             allQuestions = (singleText!.text.isNotEmpty
  //                     ? int.parse(singleText!.text)
  //                     : 0) +
  //                 (judgmentText!.text.isNotEmpty
  //                     ? int.parse(judgmentText!.text)
  //                     : 0);
  //           }
  //           if (int.parse(judgmentText!.text) > mDataEq!.pdNum!) {
  //             judgmentText!.text = mDataEq!.pdNum!.toString();
  //             allQuestions = (singleText!.text.isNotEmpty
  //                     ? int.parse(singleText!.text)
  //                     : 0) +
  //                 (judgmentText!.text.isNotEmpty
  //                     ? int.parse(judgmentText!.text)
  //                     : 0);
  //           }
  //         }
  //       });
  //     }
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: Stack(
        children: [
          Image.asset('assets/home/rigister_bg.png'),
          Container(
            height: 280,
            margin:
                const EdgeInsets.only(left: 15, top: 130, right: 15, bottom: 0),
            decoration: const BoxDecoration(
              color: ColorConst.whiteColor,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: CustomScrollView(
              primary: false,
              shrinkWrap: true,
              slivers: <Widget>[
                SliverToBoxAdapter(
                  child: Column(
                    children: [
                      buildUnitInformation(),
                      buildSubmit()
                      // const SizedBox(height: 30)
                    ],
                  ),
                ),
              ],
            ),
          ),
          buildTopTitle(context)
        ],
      ),
    );
  }

  ///单位信息
  Container buildUnitInformation() {
    return Container(
      margin: const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const SizedBox(height: 10),
          const Row(children: [
            Icon(Icons.touch_app, color: ColorConst.orangeColor, size: 15),
            Text('设备类型', style: TextStyle(fontSize: 14))
          ]),
          const SizedBox(height: 5),
          CustomTextField(
              enabled: true,
              readOnly: true,
              hintText: '请选择设备类型',
              controller: equipmentText,
              focusNode: equipmentFocusNode,
              onTop: () {
                Get.toNamed(RouteString.EQUIPMENT_LIST_PAGE, arguments: {
                  'officeId': StorageUtil.getInstance().getOfficeId()
                })?.then((map) {
                  if (map != null) {
                    mEquiList = map;
                    setState(() {
                      equipmentText!.text = mEquiList!.name!;
                      // getFindEqQuestionNum(false);
                    });
                  }
                });
              }),
          const SizedBox(height: 10),
          Row(children: [
            const Icon(Icons.touch_app,
                color: ColorConst.orangeColor, size: 15),
            Text('身份${unitType == "1" ? "-(使用单位)" : "-(生产单位)"}',
                style: const TextStyle(fontSize: 14))
          ]),
          const SizedBox(height: 5),
          CustomTextField(
              enabled: true,
              readOnly: true,
              hintText: '请选择身份',
              controller: roleText,
              focusNode: roleFocusNode,
              onTop: () {
                showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        contentPadding: EdgeInsets.all(0.0),
                        titlePadding: const EdgeInsets.only(
                            left: 20, right: 20, top: 20, bottom: 10),
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text('请选择您的身份'),
                            InkWell(
                              onTap: () {
                                Get.back();
                              },
                              child: const Icon(
                                Icons.clear,
                                size: 30,
                                color: Colors.grey,
                              ),
                            )
                          ],
                        ),
                        content: SingleChildScrollView(
                          physics: const NeverScrollableScrollPhysics(),
                          child: Column(
                            children: [
                              buildListContent(),
                              Container(
                                height: 10,
                              )
                            ],
                          ),
                        ),
                      );
                    });

                // showDialog(
                //   context: context,
                //   builder: (context) {
                //     return AlertDialog(
                //       titlePadding: const EdgeInsets.only(
                //           left: 20, right: 20, top: 20, bottom: 0),
                //       title: Row(
                //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //         children: [
                //           const Text('请选择您的身份'),
                //           InkWell(
                //             onTap: () {
                //               Get.back();
                //             },
                //             child: const Icon(
                //               Icons.clear,
                //               size: 30,
                //               color: Colors.grey,
                //             ),
                //           )
                //         ],
                //       ),
                //       content: StatefulBuilder(
                //         builder: (context, StateSetter setState) {
                //           return ListView.builder(
                //             shrinkWrap: true,
                //             itemCount: roleUserLists!.length,
                //             itemBuilder: (context, index) {
                //               return ListTile(
                //                 title: Text(roleUserLists![index].roleName!),
                //                 onTap: () {
                //                   setState(() {
                //                     roleText!.text =
                //                         roleUserLists![index].roleName!;
                //                     roleId = roleUserLists![index].roleId!;
                //                     Navigator.pop(context); // 关闭弹窗
                //                   });
                //                 },
                //               );
                //             },
                //           );
                //         },
                //       ),
                //     );
                //   },
                // );

                // Get.toNamed(RouteString.EQUIPMENT_LIST_PAGE, arguments: {
                //   'officeId': StorageUtil.getInstance().getOfficeId()
                // })?.then((map) {
                //   if (map != null) {
                //     mEquiList = map;
                //     setState(() {
                //       equipmentText!.text = mEquiList!.name!;
                //       // getFindEqQuestionNum(false);
                //     });
                //   }
                // });
              }),
          // const Tip('小提示:【安全员、安全总监】身份可进行测试练习', marginLeft: 5),
          const Tip('小提示:【安全员、安全总监】可进行测试练习',
              marginLeft: 5, marginTop: 5, marginRight: 10),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget buildListContent() {
    List<InkWell> textList = [];
    for (var item in roleUserLists!) {
      textList.add(InkWell(
        onTap: () {
          setState(() {
            roleText!.text = item.roleName!;
            roleId = item.roleId!;
            Navigator.pop(context); // 关闭弹窗
          });
        },
        child: Container(
          width: double.infinity,
          padding:
              const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 10),
          child: Text(item.roleName!, textAlign: TextAlign.center),
        ),
      ));
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: textList,
    );
  }

  Container buildTopTitle(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 50),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          IconButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            iconSize: 30,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: const Text(
                    '测试练习设置',
                    style: TextStyle(
                        fontSize: 23,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  )),
              Container(
                  height: 3,
                  width: 50,
                  alignment: Alignment.topLeft,
                  margin: const EdgeInsets.only(top: 3, bottom: 3),
                  decoration: const BoxDecoration(
                    color: Colors.white54,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  )),
              const Text(
                '',
                style: TextStyle(fontSize: 12, color: Colors.white),
              ),
            ],
          ),
        ],
      ),
    );
  }

  ///交卷
  Container buildSubmit() {
    return Container(
        // margin: const EdgeInsets.only(top: 10, bottom: 0),
        padding: const EdgeInsets.only(left: 20, right: 20, top: 15, bottom: 0),
        width: double.infinity,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: GradientButton(
            tapCallback: () {
              if (equipmentText!.text.isEmpty) {
                ToastUtils.showCenter('请选择设备类型');
                return;
              }
              if (roleText!.text.isEmpty) {
                ToastUtils.showCenter('请选择身份');
                return;
              }
              // if (allQuestions == 0) {
              //   ToastUtils.showCenter('总题数不能为 0');
              //   return;
              // }
              TestSubmitBo mTestSubmitBo = TestSubmitBo();
              mTestSubmitBo.mEquiList = mEquiList;
              // mTestSubmitBo.dxQuestionsNum =
              //     singleText!.text.isNotEmpty ? int.parse(singleText!.text) : 0;
              // mTestSubmitBo.pdQuestionsNum = judgmentText!.text.isNotEmpty
              //     ? int.parse(judgmentText!.text)
              //     : 0;
              Get.offNamed(RouteString.TEST_PAGE, arguments: {
                'mTestSubmitBo': mTestSubmitBo,
                'positionType': roleId
              })?.then((value) {
                if (value != null && value) {}
              });
            },
            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),
            )));
  }
}
