// ignore_for_file: use_build_context_synchronously, sort_child_properties_last, unnecessary_null_comparison, prefer_typing_uninitialized_variables

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/edgeInsets_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/app_is_open.dart';
import 'package:special_equipment_flutter/model/login_bo.dart';
import 'package:special_equipment_flutter/model/user_bo.dart';
import 'package:special_equipment_flutter/ui/common/data.dart';
import 'package:special_equipment_flutter/utils/sp_account_utils.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/tip.dart';

import '../../dio/api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return LoginState();
  }
}

class LoginState extends State<LoginPage> {
  @override
  void initState() {
    super.initState();
    StorageUtil.getInstance().init();
  }

  @override
  Widget build(BuildContext context) {
    return const EditTextWidget();
  }
}

class EditTextWidget extends StatefulWidget {
  const EditTextWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return EditTextState();
  }
}

class LightPainter extends CustomPainter {
  final Animation<double> _animation;

  LightPainter() : _animation = const AlwaysStoppedAnimation(0);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..shader = LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: const [Colors.transparent, Colors.white, Colors.transparent],
        stops: [
          _animation.value - 0.2,
          _animation.value,
          _animation.value + 0.2,
        ],
      ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
  }

  @override
  bool shouldRepaint(LightPainter oldDelegate) => false;
}

class EditTextState extends State<EditTextWidget>
    with SingleTickerProviderStateMixin {
  //控制器
  late TextEditingController phoneController;
  late TextEditingController passController;
  final List<Item> listItems = <Item>[
    Item(title: '使用单位', unitType: '1', checked: true),
    Item(title: '生产单位', unitType: '2', checked: false),
  ];

  late final AnimationController logoController;
  late final Animation<double> logoAnimation;
  var versionName;
  String? isOpen = '0';
  bool isPassword = true;

  @override
  void initState() {
    _initPackageInfo();
    getAccountList();
    phoneController = TextEditingController();
    passController = TextEditingController();
    phoneController.addListener(() {
      //清除文字触发
      setState(() {});
    });

    phoneController.value = phoneController.value.copyWith(
        text: Api.IS_DEBUG ? StorageUtil.getInstance().getUserName() : 'tyjcr');
    passController.value = passController.value.copyWith(
        text: Api.IS_DEBUG
            ? StorageUtil.getInstance().getPassword()
            : 'Aa123456.');
    super.initState();

    logoController = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    )..forward();

    logoAnimation = CurvedAnimation(
      parent: logoController,
      curve: Curves.bounceOut,
    );

    if (Platform.isIOS) {
      HttpUtils.doAppIsOpen(context, onSuccess: (value) {
        AppIsOpen appIsOpen = value;
        if (mounted) {
          setState(() {
            isOpen = appIsOpen.appIsOpen!;
          });
        }
      });
    }
  }

  Future<void> _initPackageInfo() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    setState(() {
      versionName = info.version;
    });
  }

  @override
  void dispose() {
    phoneController.dispose();
    passController.dispose();
    logoController.dispose();
    super.dispose();
  }

  void exitClick() {
    //如果flutter作为module依赖，则原生也需要处理退出app，由原生来退出整个app
//    SystemNavigator.pop();
    exit(0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          height: double.infinity,
          margin: const EdgeInsets.only(left: 30, right: 30, top: 50),
          child: Column(
            children: <Widget>[
              Container(
                  alignment: Alignment.centerLeft,
                  child: IconButton(
                    onPressed: exitClick,
                    icon: const Icon(Icons.clear),
                    iconSize: 30,
                  )),
//          buildTitleLine(),
              Container(
                  margin: const EdgeInsets.only(top: 50),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          SizedBox(
                            width: 30.0, //容器宽度
                            height: 30.0, //容器高度
                            child: AnimatedBuilder(
                              animation: logoAnimation,
                              builder: (context, child) {
                                return Transform.scale(
                                  scale: logoAnimation.value,
                                  child: ClipRRect(
                                      borderRadius: BorderRadius.circular(5.0),
                                      child:
                                          Image.asset('assets/home/logo.png')),
                                );
                              },
                            ),
                          ),
                          const SizedBox(width: 5),
                          buildTitle()
                        ],
                      ),

                      buildTips(),
                      const SizedBox(height: 30),

                      accountTextField(context),
                      //账号
                      const SizedBox(height: 12),
                      //账号和密码间距
                      buildPasswordTextField(context),
                      //密码

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                isPassword = !isPassword;
                              });
                            },
                            child: Row(
                              children: [
                                Container(
                                  width: 30,
                                  margin: const EdgeInsets.only(left: 35),
                                  child: Checkbox(
                                    value: isPassword,
                                    onChanged: (bool? value) {
                                      setState(() {
                                        isPassword =
                                            value!; // 更新 isChecked 的状态值
                                      });
                                    },
                                  ),
                                ),
                                Container(
                                  child: const Text('记住密码'),
                                  margin: const EdgeInsets.only(bottom: 3),
                                ),
                              ],
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              // List<UserBo> userList =
                              //     StorageUtil.getInstance().getUserList();
                              setState(() {
                                if (listAccount.isNotEmpty) {
                                  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: (BuildContext context) {
                                  //     return AlertDialog(
                                  //       titlePadding: const EdgeInsets.only(
                                  //           left: 20,
                                  //           right: 20,
                                  //           top: 10,
                                  //           bottom: 10),
                                  //       title: Row(
                                  //         mainAxisAlignment:
                                  //             MainAxisAlignment.spaceBetween,
                                  //         children: [
                                  //           const Text('历史登录账号、密码'),
                                  //           InkWell(
                                  //             onTap: () {
                                  //               Get.back();
                                  //             },
                                  //             child: const Icon(
                                  //               Icons.clear,
                                  //               size: 30,
                                  //               color: Colors.grey,
                                  //             ),
                                  //           )
                                  //         ],
                                  //       ),
                                  //       actions: <Widget>[
                                  //         ListView.separated(
                                  //           scrollDirection: Axis.vertical,
                                  //           shrinkWrap: true,
                                  //           itemCount: listAccount.length,
                                  //           itemBuilder: (BuildContext context,
                                  //               int index) {
                                  //             return InkWell(
                                  //               splashColor:
                                  //                   ColorConst.themeBgColor,
                                  //               onTap: () {
                                  //                 setState(() {
                                  //                   phoneController.value =
                                  //                       phoneController.value
                                  //                           .copyWith(
                                  //                               text: listAccount[
                                  //                                       index]
                                  //                                   .account);
                                  //                   passController.value =
                                  //                       passController.value
                                  //                           .copyWith(
                                  //                               text: listAccount[
                                  //                                       index]
                                  //                                   .password);
                                  //                   Get.back();
                                  //                 });
                                  //               },
                                  //               child: Padding(
                                  //                 padding:
                                  //                     const EdgeInsets.only(
                                  //                         left: 10),
                                  //                 child: Row(
                                  //                   mainAxisAlignment:
                                  //                       MainAxisAlignment
                                  //                           .spaceBetween,
                                  //                   children: [
                                  //                     Row(
                                  //                       children: [
                                  //                         const Icon(
                                  //                           Icons.person,
                                  //                           size: 20,
                                  //                           color: Colors.grey,
                                  //                         ),
                                  //                         Text(
                                  //                           listAccount[index]
                                  //                               .account!,
                                  //                           style: const TextStyle(
                                  //                               fontSize: 16,
                                  //                               color: ColorConst
                                  //                                   .blueColor),
                                  //                         ),
                                  //                       ],
                                  //                     ),
                                  //                     InkWell(
                                  //                       onTap: () {
                                  //                         setState(() {
                                  //                           showDialog(
                                  //                               context:
                                  //                                   context,
                                  //                               builder:
                                  //                                   (context) {
                                  //                                 return AlertDialog(
                                  //                                   content: Text(
                                  //                                       "您确定要清除【${listAccount[index].account}】这个历史纪录账号吗？"),
                                  //                                   actions: [
                                  //                                     TextButton(
                                  //                                       child: const Text(
                                  //                                           "取消"),
                                  //                                       onPressed:
                                  //                                           () {
                                  //                                         Navigator.of(context)
                                  //                                             .pop();
                                  //                                       },
                                  //                                     ),
                                  //                                     TextButton(
                                  //                                         child: const Text(
                                  //                                             "确定"),
                                  //                                         onPressed:
                                  //                                             () {
                                  //                                           ToastUtils.showCenter("已清除【${listAccount[index].account}】的历史账号");
                                  //                                           SPAccountUtil.delUser(listAccount[index],
                                  //                                               index);
                                  //                                           debugPrint(jsonEncode(listAccount));
                                  //                                           listAccount.remove(listAccount[index]);
                                  //                                           Get.back();
                                  //                                           Get.back();
                                  //                                         })
                                  //                                   ],
                                  //                                 );
                                  //                               });
                                  //                         });
                                  //                       },
                                  //                       child: const Padding(
                                  //                         padding:
                                  //                             EdgeInsets.all(
                                  //                                 13.0),
                                  //                         child: Icon(
                                  //                           Icons.clear,
                                  //                           size: 18,
                                  //                           color: Colors.grey,
                                  //                         ),
                                  //                       ),
                                  //                     )
                                  //                   ],
                                  //                 ),
                                  //               ),
                                  //             );
                                  //           },
                                  //           separatorBuilder:
                                  //               (BuildContext context,
                                  //                   int index) {
                                  //             return Container(
                                  //               height: 1,
                                  //               color: Colors.grey[100],
                                  //             );
                                  //           },
                                  //         )
                                  //       ],
                                  //     );
                                  //   },
                                  // );
                                } else {
                                  ToastUtils.showCenter('暂无历史登录账号');
                                }
                              });
                            },
                            child: Container(
                              margin: const EdgeInsets.only(bottom: 3),
                              padding: const EdgeInsets.all(10),
                              child: const Text(
                                '历史登录账号>',
                                style: TextStyle(color: ColorConst.blueColor),
                              ),
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 40), //密码和登录按钮间距
                      //嵌套SizedBox, 设置button的宽高
                      buildLogin(),
                      if (Platform.isIOS) ...[
                        if (isOpen == '1') ...[
                          const SizedBox(height: 15), //密码和登录按钮间距
                          buildRigister(),
                          const Tip('初次使用，请先完成单位账号注册',
                              marginTop: 0, width: 280),
                        ]
                      ] else ...[
                        const SizedBox(height: 15), //密码和登录按钮间距
                        buildRigister(),
                        const Tip('初次使用，请先完成单位账号注册', marginTop: 0, width: 280),
                      ]
                    ],
                  )),
              const Spacer(),
              const Align(
                alignment: Alignment.bottomCenter,
                child: Text('晋ICP备19001455号-3A',
                    style: TextStyle(color: Colors.grey)),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Text('版本: $versionName',
                    style: const TextStyle(color: Colors.grey)),
              ),
              const SizedBox(height: 25) //版本号底部距离
            ],
          ),
        ));
  }

  Widget buildListContent() {
    List<InkWell> textList = [];
    for (int index = 0; index < listAccount.length; index++) {
      textList.add(InkWell(
        splashColor: ColorConst.themeBgColor,
        onTap: () {
          setState(() {
            phoneController.value = phoneController.value
                .copyWith(text: listAccount[index].account);
            passController.value = passController.value
                .copyWith(text: listAccount[index].password);
            Get.back();
          });
        },
        child: Container(
          width: double.infinity,
          padding:
              const EdgeInsets.only(left: 20, top: 0, right: 10, bottom: 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  const Icon(
                    Icons.person,
                    size: 20,
                    color: Colors.grey,
                  ),
                  Text(
                    listAccount[index].account!,
                    style: const TextStyle(
                        fontSize: 16, color: ColorConst.blueColor),
                  ),
                ],
              ),
              InkWell(
                onTap: () {
                  setState(() {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            content: Text(
                                "您确定要清除【${listAccount[index].account}】这个历史纪录账号吗？"),
                            actions: [
                              TextButton(
                                child: const Text("取消"),
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                              ),
                              TextButton(
                                  child: const Text("确定"),
                                  onPressed: () {
                                    ToastUtils.showCenter(
                                        "已清除【${listAccount[index].account}】的历史账号");
                                    SPAccountUtil.delUser(
                                        listAccount[index], index);
                                    debugPrint(jsonEncode(listAccount));
                                    listAccount.remove(listAccount[index]);
                                    Get.back();
                                    Get.back();
                                  })
                            ],
                          );
                        });
                  });
                },
                child: const Padding(
                  padding: EdgeInsets.all(13.0),
                  child: Icon(
                    Icons.clear,
                    size: 18,
                    color: Colors.grey,
                  ),
                ),
              )
            ],
          ),
        ),
      ));
    }

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

  List<UserBo> listAccount = [];

  ///获取历史用户
  void getAccountList() async {
    listAccount.clear();
    listAccount.addAll(await SPAccountUtil.getUsers());
  }

  GradientButton buildRigister() {
    return GradientButton(
        tapCallback: () {
          Get.toNamed(RouteString.REGISTER1);
        },
        width: 280,
        height: 40,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(5),
            topRight: Radius.circular(15),
            bottomLeft: Radius.circular(15),
            bottomRight: Radius.circular(5)),
        disable: false,
        colors: const [Colors.blue, ColorConst.blueColor],
        child: const Text(
          "注册（单位账户）",
          style: TextStyle(fontSize: 16, color: ColorConst.whiteColor),
        ));
  }

  GradientButton buildLogin() {
    return GradientButton(
        tapCallback: () {
          _loginClick();
        },
        width: 280,
        height: 40,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(5),
            topRight: Radius.circular(15),
            bottomLeft: Radius.circular(15),
            bottomRight: Radius.circular(5)),
        disable: false,
        colors: const [ColorConst.blueColor, Colors.blue],
        child: const Text(
          "登录",
          style: TextStyle(fontSize: 16, color: ColorConst.whiteColor),
        ));
  }

  ///登录按钮
  Widget buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 40,
        width: 280,
        child: ElevatedButton(
//          style: ButtonStyle(
//              // 设置圆角
//              shape: MaterialStateProperty.all(const StadiumBorder(
//                  side: BorderSide(style: BorderStyle.none)))),
          child: const Text('登录', style: TextStyle(fontSize: 16)),
          onPressed: _loginClick,
        ),
      ),
    );
  }

  Widget buildTitle() {
    return const Text(
      '晋特保助手',
      style: TextStyle(
          fontSize: 25,
          color: ColorConst.blueColor,
          fontWeight: FontWeight.bold),
    );
  }

  Widget buildTips() {
    return const Padding(
        // 设置边距
        padding: EdgeInsets.only(top: 5, bottom: 5, right: 5),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Text(
            '您好，请在下方输入账号/手机号、密码进行登录',
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ));
  }

  Widget buildTitleLine() {
    return Padding(
        padding: const EdgeInsets.only(left: 12.0, top: 4.0),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            color: Colors.black,
            width: 40,
            height: 2,
          ),
        ));
  }

  bool _isObscure = true;
  Color _eyeColor = Colors.grey;

  ///密码输入框
  Widget buildPasswordTextField(BuildContext context) {
    return TextFormField(
        obscureText: _isObscure,
        // 是否显示文字
        autofocus: false,
        keyboardType: TextInputType.text,
        controller: passController,
        maxLines: 1,
        validator: (v) {
          if (v!.isEmpty) {
            return '请输入密码';
          }
          return null;
        },
        decoration: InputDecoration(
            labelText: "请输入密码",
            contentPadding: const EdgeInsets.all(10),
            icon: const Icon(Icons.lock_outline),
            iconColor: ColorConst.themeBgColor,
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              iconSize: 20,
              onPressed: () {
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor =
                      (_isObscure ? Colors.grey : ColorConst.themeBgColor);
                });
              },
            )));
  }

  Widget accountTextField(BuildContext context) {
    return TextField(
      keyboardType: TextInputType.text,
      maxLines: 1,
      controller: phoneController,
      decoration: InputDecoration(
          contentPadding: const EdgeInsets.all(10),
          icon: const Icon(Icons.phone_android),
          iconColor: ColorConst.themeBgColor,
          labelText: "请输入账号",
          suffixIcon: phoneController.text.isNotEmpty
              ? IconButton(
                  icon: const Icon(
                    Icons.clear,
                    color: Colors.grey,
                  ),
                  iconSize: 20,
                  onPressed: () {
                    setState(() {
                      phoneController.clear();
                    });
                  },
                )
              : null),
      autofocus: false,
    );
  }

  void _loginClick() {
    String hint = "";
    var userName = phoneController.text.trim();
    var pwd = passController.text.trim();

    if (userName.isEmpty) {
      hint = "账号不能为空";
    } else if (userName.length < 3) {
      hint = "账号至少3位数";
    } else if (pwd.isEmpty) {
      hint = "密码不能为空";
    }
    if (hint.isNotEmpty) {
      ToastUtils.showCenter(hint);
      return;
    }
    // phoneController.clear();
    // passController.clear();
    _startLogin(userName, pwd);
  }

  Future<dynamic> showUnitTypeDialog(split) {
    return showDialog(
      context: context,
      builder: (context) {
        return UnconstrainedBox(
          //在Dialog的外层添加一层UnconstrainedBox
          constrainedAxis: Axis.vertical,
          child: SizedBox(
            width: MediaQuery.of(context).size.width * 0.7,
            child: Dialog(
              insetPadding: EdgeInsets.zero,
              child: StatefulBuilder(builder: (context, setState) {
                return SizedBox(
                  height: 220,
                  child: Padding(
                    padding: const EdgeInsets.only(
                        top: 15, left: 10, right: 10, bottom: 0),
                    child: Column(
                      children: [
                        const Text(
                          '请选择您的单位类别',
                          style: TextStyle(
                              fontSize: 18,
                              color: Colors.black,
                              fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        ListView.builder(
                          shrinkWrap: true,
                          itemBuilder: (BuildContext context, int index) {
                            return Center(
                              child: InkWell(
                                splashColor: ColorConst.blue1Color,
                                onTap: () {
                                  setState(() {
                                    for (var item in listItems) {
                                      item.checked = false;
                                    }
                                    listItems[index].checked = true;
                                  });
                                },
                                child: Padding(
                                  padding: const EdgeInsets.all(10.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(listItems[index].title,
                                          style: TextStyle(
                                              fontSize: 16,
                                              color: listItems[index].checked
                                                  ? ColorConst.greenColor
                                                  : Colors.black)),
                                      const SizedBox(
                                        width: 5,
                                      ),
                                      Icon(
                                          listItems[index].checked
                                              ? Icons.check_circle
                                              : Icons.panorama_fisheye,
                                          color: listItems[index].checked
                                              ? ColorConst.greenColor
                                              : ColorConst.greyC2Color,
                                          size: EdgeInsetsConst
                                              .single_choice_icon_size),
                                    ],
                                  ),
                                ),
                              ),
                            );
                          },
                          itemCount: listItems.length,
                        ),
                        const SizedBox(
                          height: 25,
                        ),
                        InkWell(
                          onTap: () {
                            for (var item in listItems) {
                              if (item.checked) {
                                if (item.unitType == '1') {
                                  StorageUtil.getInstance()
                                      .set(SpKeys.UNIT_STATUS, split[0]);
                                  Navigator.of(context).pop();
                                  Get.offAllNamed(RouteString.HOME);
                                  break;
                                } else {
                                  StorageUtil.getInstance()
                                      .set(SpKeys.UNIT_STATUS, split[1]);
                                  Navigator.of(context).pop();
                                  Get.offAllNamed(RouteString.HOME);
                                  break;
                                }
                              }
                            }
                          },
                          child: Container(
                            alignment: Alignment.center,
                            width: MediaQuery.of(context).size.width * 0.6,
                            height: 40,
                            decoration: const BoxDecoration(
                              color: ColorConst.blueColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                            ),
                            // color: ColorConst.blueColor,
                            child: const Text("确定",
                                style: TextStyle(
                                    fontSize: 16,
                                    color: ColorConst.whiteColor)),
                          ),
                        )
                      ],
                    ),
                  ),
                );
              }),
            ),
          ),
        );
      },
    );
  }

//登录
  _startLogin(userName, pwd) async {
    ///清除本地所有数据
    // StorageUtil.getInstance().clearAll();
    StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
    HttpUtils.doLogin(context, userName, pwd, onSuccess: (value) {
      if (value != null) {
        LoginBo loginBo = value;
        StorageUtil.getInstance().set(SpKeys.USER_NAME, loginBo.username);
        StorageUtil.getInstance().set(SpKeys.PASSWORD, pwd);
        StorageUtil.getInstance().set(SpKeys.NAME, loginBo.name);
        StorageUtil.getInstance().set(SpKeys.JSESSION_ID, loginBo.jsessionid);
        StorageUtil.getInstance().set(SpKeys.USER_ID, loginBo.userId);
        StorageUtil.getInstance()
            .set(SpKeys.OFFICE_ID, loginBo.user!.office!.id);
        StorageUtil.getInstance()
            .set(SpKeys.OFFICE_TYPE, loginBo.user!.office!.type);
        StorageUtil.getInstance()
            .set(SpKeys.OFFICE_NAME, loginBo.user!.office!.name);
        StorageUtil.getInstance()
            .set(SpKeys.ROLE_NAMES, loginBo.user!.roleNames);

        ///记住密码
        if (isPassword) {
          ///将账号密码保存到本地历史纪录
          SPAccountUtil.saveUser(UserBo(userName, pwd));
          SPAccountUtil.addNoRepeat(listAccount, UserBo(userName, pwd));
          debugPrint(jsonEncode(listAccount));
        }

        ///公司账户
        if (isUnitRoles(loginBo.user!.roleNames)!) {
          Get.offAllNamed(RouteString.HOME);
        } else {
          var split = loginBo.user!.office!.type!.split(",");
          switch (split.length) {
            case 1:
              StorageUtil.getInstance().set(SpKeys.UNIT_STATUS, split[0]);
              Get.offAllNamed(RouteString.HOME);
              break;
            case 2:
              showUnitTypeDialog(split);
              break;
          }
        }
      }
    });

    // HttpUtils.doLogin(context, username, pwd).then((value) {
    //   if (value != null) {
    //     LoginBo loginBo = value;
    //     StorageUtil.getInstance().set(SpKeys.USER_NAME, loginBo.username);
    //     StorageUtil.getInstance().set(SpKeys.NAME, loginBo.name);
    //     StorageUtil.getInstance().set(SpKeys.JSESSION_ID, loginBo.jsessionid);
    //     StorageUtil.getInstance().set(SpKeys.USER_ID, loginBo.userId);
    //     StorageUtil.getInstance()
    //         .set(SpKeys.OFFICE_ID, loginBo.user!.office!.id);
    //     StorageUtil.getInstance()
    //         .set(SpKeys.OFFICE_TYPE, loginBo.user!.office!.type);
    //     StorageUtil.getInstance()
    //         .set(SpKeys.OFFICE_NAME, loginBo.user!.office!.name);
    //     StorageUtil.getInstance()
    //         .set(SpKeys.ROLE_NAMES, loginBo.user!.roleNames);
    //
    //     ///公司账户
    //     if (isUnitRoles(loginBo.user!.roleNames)!) {
    //       Get.offAllNamed(RouteString.HOME);
    //     } else {
    //       var split = loginBo.user!.office!.type!.split(",");
    //       switch (split.length) {
    //         case 1:
    //           StorageUtil.getInstance().set(SpKeys.UNIT_STATUS, split[0]);
    //           Get.offAllNamed(RouteString.HOME);
    //           break;
    //         case 2:
    //           showUnitTypeDialog(split);
    //           break;
    //       }
    //     }
    //   }
    // });
  }
}

class Item {
  Item({this.checked, this.unitType, this.title});

  var checked;
  var unitType;
  var title;
}
