// ignore_for_file: use_build_context_synchronously, sort_child_properties_last, unnecessary_null_comparison, prefer_typing_uninitialized_variables

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/ui/common/data.dart';
import 'package:special_equipment_flutter/utils/sp_util.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 '../../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';

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

    phoneController.value =
        phoneController.value.copyWith(text: Api.IS_DEBUG ? '' : 'csgs123');
    passController.value =
        passController.value.copyWith(text: Api.IS_DEBUG ? '' : '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')),
                                );
                              },
                            ),
                          ),
                          buildTitle()
                        ],
                      ),

                      buildTips(),
                      const SizedBox(height: 30),
                      accountTextField(context), //账号
                      const SizedBox(height: 12), //账号和密码间距
                      buildPasswordTextField(context), //密码
                      const SizedBox(height: 40), //密码和登录按钮间距
                      //嵌套SizedBox, 设置button的宽高
                      buildLogin(),
                      if (Platform.isIOS) ...[
                        if (isOpen == '1') ...[
                          const SizedBox(height: 15), //密码和登录按钮间距
                          buildRigister()
                        ]
                      ] else ...[
                        const SizedBox(height: 15), //密码和登录按钮间距
                        buildRigister()
                      ]
                    ],
                  )),
              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) //版本号底部距离
            ],
          ),
        ));
  }

  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 Padding(
        // 设置边距
        padding: EdgeInsets.all(5),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Text(
            '欢迎登录',
            style: TextStyle(
              fontSize: 25,
              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();
    SPUtil().clearAll();
    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;
}
