import 'dart:convert';

import 'package:ai_save_account/ai_save_account.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hyzp_ybqx/pages/Works/TJXX/tj_data.dart';

import '../../components/EncryptUtil.dart';
import '../../components/commonFun.dart';
import '../../config/service_url.dart';
import '../../services/EventBus.dart';
import '../../services/Storage.dart';
import '../../widget/JdText.dart';

class LoginByName3 extends StatefulWidget {
  LoginByName3({Key key, this.height}) : super(key: key);
  double height;

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginByName3> {
  //try_setState();   //避免如下异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  //监听登录页面销毁的事件
  dispose() {
    super.dispose();
    eventBus.fire(new UserEvent('登录成功...'));
  }

  bool bRemmberPW = false;

  GlobalKey _globalKey = new GlobalKey(); //用来标记控件
  // bool g_can_expand_ListView = false; //是否能够打开历史账号
  // List<UserAccount> g_users = new List(); //历史账号

  @override
  void initState() {
    super.initState();
    // g_userInfo.username = 'the_user_03';
    // g_userInfo.password = '123456';
    // g_userInfo.password = 'ybhb1234';
    g_userInfo.username = '';
    g_userInfo.password = '';
    doInit();

    //监听统计数据改变事件
    eventBus.on<StatisDataUpdate>().listen((event) {
      print(event.str);
      updateMayLogin();
    });
  }

  // 一套APP适应多个区县登录过程05、处理延迟登录。等待预加载数据成功后，进行页面跳转
  updateMayLogin() {
    //判断从网络获取三种统计数据是否完成
    // if (listZptjStatisAlone.length >= dwSum &&
    //     listTodayShtj.length >= dwSum &&
    //     listClltjStatisAlone.length >= dwSum) {
    //   bMayLogin = true;
    // }
    if (listAllStatisData.length >= dwSum) {
      bMayLogin = true;
    }

    if (bMayLogin && bLoginVerify) {
      //重新初始化处理延时登录的变量
      // bMayLogin = false;
      // bPreLoading = false;
      // bLoginVerify = false; //处理延时登录，判断用户名登录是否验证通过

      Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);
      // Future.delayed(const Duration(milliseconds: 1000), () {
      // });
    }
  }

  doInit() async {
    bRemmberPW = await Storage.getBool('bRemmberPW');
    bRemmberPW = (null == bRemmberPW) ? false : bRemmberPW;
    print('bRemmberPW = $bRemmberPW');

    if (bRemmberPW) {
      //取出后需解密
      g_userInfo.username = await Storage.getString('username');
      g_userInfo.username = EncryptUtil.aesDecode(g_userInfo.username);
      g_userInfo.password = await Storage.getString('password');
      g_userInfo.password = EncryptUtil.aesDecode(g_userInfo.password);

      //user account list
      _gainUsers();
    }
    try_setState();
  }

  doLogin() async {
    //测试用，临时绕过登录处理
    // Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);
    // return;

    // if (!bMayLogin) {
    //   bPreLoading = true;
    //   try_setState();
    // }

    // 一套APP适应多个区县登录过程01、显示“加载中 ...”
    bPreLoading = true;
    try_setState();

    var api = ServicePath.loginUrl;
    print(api);
    try {
      print('开始处理登录请求...');
      print('username = ${g_userInfo.username}');
      print('password = ${g_userInfo.password}');
      Response response;
      Dio dio = Dio();

      String random = RandomBit(6); //flutter （dart）生成N位随机数
      print('random = ${random}');
      print('sign = ${GenerateMd5(APPkey + random)}');

      response = await dio.post(api, data: {
        "username": g_userInfo.username,
        "password": g_userInfo.password,
        "sign": GenerateMd5(APPkey + random),
        "random": random,
      });
      print('response = ${response.toString()}');
      //I/flutter ( 5242): {"ret":200,"data":{"is_login":true,"user_id":3,"token":"32EE57A0109A3D1D6590CFD3DEBA71820F77AB654093C1DE750347C88D1A41CF"},"msg":""}
      if (response.statusCode == 200) {
        // Storage.setString('userInfo', json.encode(response.data["userinfo"]));
        // //Navigator.pop(context);
        // Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);

        //print('response.data["data"]["is_login"] = ${response.data["data"]["is_login"]}');
        //I/flutter ( 5242): response.data["data"]["is_login"] = true

        //{
        //     "ret": 200,
        //     "data": {
        //         "is_login": true,
        //         "user_id": 1,
        //         "token": "B93EC91FA2FE293B7077162D4527FC4BB228CD6C0A4F24A882B9A8BBE6C3FB47"
        //     },
        //     "msg": ""
        // }

        print('response = ${response}');
        //response = {"ret":406,"data":{},"msg":"非法请求：签名错误"}
        if (true == response.data["data"]["is_login"]) {
          print('登录成功');
          print('response.data = ${response.data}');

          // 一套APP适应多个区县登录过程02、进行登录验证，保存登录信息
          if (bRemmberPW) {
            Storage.setBool('bRemmberPW', bRemmberPW);
            //加密保存
            Storage.setString('username', EncryptUtil.aesEncode(g_userInfo.username));
            Storage.setString('password', EncryptUtil.aesEncode(g_userInfo.password));
            //保存帐号密码列表
            SaveAccountPasswordManager.saveUser(
                UserAccount(g_userInfo.username, g_userInfo.password));
          } else {
            Storage.remove('username');
            Storage.remove('password');
            //清空帐号密码列表
            SaveAccountPasswordManager.getUsers().then((listUsers) {
              for (var user in listUsers) {
                print("User = ${user}");
                SaveAccountPasswordManager.delUser(user);
              }
            });
          }

          // 一套APP适应多个区县登录过程03、登录成功，保存登录信息
          Storage.setString('userInfo', json.encode(response.data["data"]));
          g_userInfo
              .setUserInfo(theMapUserInfoRet: await getMapFromJson(response.data))
              .then((value) {
            // 一套APP适应多个区县登录过程04、登录成功，开始使用保存的登录信息预加载数据，并设置bLoginVerify = true
            bLoginVerify = true; //处理延时登录，判断用户名登录是否验证通过
            startGetStatisDataNew(); // 2、登录前提前获取统计数据，改善用户登录体验
            // Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);
          });
          //获取用户所属分组和相应权限
          // getUserGroupAll().then((value) {
          //   bLoginVerify = true; //处理延时登录，判断用户名登录是否验证通过
          //   if (bMayLogin) {
          //     // bMayLogin = false;
          //     // bPreLoading = false;
          //     // bLoginVerify = false; //处理延时登录，判断用户名登录是否验证通过
          //     Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);
          //   }
          // });

          // bLoginVerify = true; //处理延时登录，判断用户名登录是否验证通过
          // Navigator.pushNamed(context, '/tabs', arguments: g_iIndex);
        } else {
          print('登录失败：${response.data["data"]}');
          bLoginVerify = false; //处理延时登录，判断用户名登录是否验证通过
          bPreLoading = false;
          try_setState(); // 登录失败后，刷新页面
          Fluttertoast.showToast(
            msg: '登录失败：用户名或密码不正确。',
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.BOTTOM,
          );
          print('登录失败：${response.data["data"]}');
        }
        print('登录过程正常完成');
      } else {
        throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
      }
    } catch (e) {
      print('登录过程异常...');
      print('ERROR:======>${e}');
      Fluttertoast.showToast(
        msg: 'ERROR:======>${e}',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }

    return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false, //解决输入法键盘弹出越界问题-无效
      backgroundColor: Colors.transparent,
      body: GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          // if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
          if (true) {
            FocusManager.instance.primaryFocus.unfocus(); // 【Flutter 实战】全局点击空白处隐藏键盘
            // 全局点击空白处隐藏账号输入框
            if (g_users.isNotEmpty) {
              //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
              // _can_expand_ListView = !_can_expand_ListView;
              g_can_expand_ListView = false;
            }
            setState(() {});
          }
        },
        child: Container(
          height: widget.height,
          child: Column(
            children: [
              Container(color: Colors.transparent, height: ScreenUtil().setHeight(45)),
              Container(
                color: Colors.white,
                width: double.infinity,
                height: ScreenUtil().setHeight(156),
                padding: EdgeInsets.only(top: 10, bottom: 0, left: 20, right: 20),
                child: JdText(
                  height: 126,
                  //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
                  title: '用户名：',
                  text: "请输入用户名",
                  onChanged: (String value) {
                    // print(value);
                    g_userInfo.username = value;
                  },
                  endBtn: 'ClearBtn',
                  // controller: TextEditingController(text: g_userInfo.username),
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: g_userInfo.username,
                      // 保持光标在最后，https://blog.csdn.net/weixin_38025168/article/details/103185466
                      selection: TextSelection.fromPosition(TextPosition(
                          affinity: TextAffinity.downstream, offset: g_userInfo.username.length)))),
                  onEndBtn: () {
                    if (g_users.isNotEmpty) {
                      //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
                      setState(() {
                        g_can_expand_ListView = !g_can_expand_ListView;
                      });
                    }
                  },
                  onEndBtn2: () {
                    // FocusManager.instance.primaryFocus.unfocus(); // 【Flutter 实战】全局点击空白处隐藏键盘
                    // 全局点击空白处隐藏账号输入框
                    // print('xx2');
                    if (g_users.isNotEmpty) {
                      //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
                      g_can_expand_ListView = false;
                    }
                    setState(() {});
                  },
                ),
              ),
              Stack(
                children: [
                  Column(
                    children: [
                      Container(
                        color: Colors.white,
                        width: double.infinity,
                        height: ScreenUtil().setHeight(224),
                        padding: EdgeInsets.only(top: 0, bottom: 20, left: 20, right: 20),
                        child: Column(
                          children: <Widget>[
                            Container(
                                color: Colors.transparent, height: ScreenUtil().setHeight(30)),
                            JdText(
                              height: 126,
                              //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
                              title: '密    码：',
                              text: "请输入密码",
                              password: true,
                              onChanged: (String value) {
                                g_userInfo.password = value;
                              },
                              endBtn: 'ShowHiddenBtn',
                              // controller: TextEditingController(text: g_userInfo.password),
                              controller: TextEditingController.fromValue(TextEditingValue(
                                  text: g_userInfo.password,
                                  // 保持光标在最后，https://blog.csdn.net/weixin_38025168/article/details/103185466
                                  selection: TextSelection.fromPosition(TextPosition(
                                      affinity: TextAffinity.downstream,
                                      offset: g_userInfo.password.length)))),
                            ),
                          ],
                        ),
                      ),
                      Container(color: Colors.transparent, height: ScreenUtil().setHeight(30)),
                      Container(
                        //color: Colors.transparent,
                        padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                        child: Row(
                          children: [
                            SizedBox(width: ScreenUtil().setWidth(45)),
                            InkWell(
                              onTap: () {
                                //Navigator.pushNamed(context, '/registerFirst');
                                this.setState(() {
                                  bRemmberPW = !bRemmberPW;
                                });
                                Storage.setBool('bRemmberPW', bRemmberPW);
                              },
                              child: Container(
                                alignment: Alignment(1, -1),
                                //width: 150,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      alignment: Alignment(0, 0),
                                      height: 22,
                                      width: 22,
                                      padding: EdgeInsets.only(top: ScreenUtil().setHeight(3)),
                                      // child: Checkbox(
                                      //   value: bRemmberPW,
                                      //   activeColor: Colors.blue,
                                      //   onChanged: (bool val) {
                                      //     this.setState(() {
                                      //       bRemmberPW = !bRemmberPW;
                                      //     });
                                      //     Storage.setBool('bRemmberPW', bRemmberPW);
                                      //   },
                                      // ),
                                      child: bRemmberPW
                                          ? Icon(Icons.check_box, color: Colors.blue)
                                          : Icon(Icons.check_box_outline_blank,
                                              color: Colors.white),
                                    ),
                                    SizedBox(width: ScreenUtil().setWidth(15)),
                                    Text('记住密码',
                                        style: TextStyle(fontSize: 17, color: Colors.white)),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: ScreenUtil().setHeight(48)),
                      InkWell(
                        onTap: doLogin,
                        child: Container(
                          alignment: Alignment(0, 0),
                          margin: EdgeInsets.all(5),
                          padding: EdgeInsets.all(5),
                          width: ScreenUtil().setWidth(999),
                          height: ScreenUtil().setHeight(126),
                          decoration: BoxDecoration(
                              color: Color.fromRGBO(23, 176, 91, 1),
                              borderRadius: BorderRadius.circular(10)),
                          child: Text(
                            bPreLoading ? "加载中 . . ." : "登    录",
                            style: TextStyle(color: Colors.white, fontSize: 18),
                          ),
                        ),
                      ),
                    ],
                  ),
                  g_users.isNotEmpty ? _buildListView() : Container(),
                ],
              ),
              // JdButton(
              //   height: 126,
              //   //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
              //   width: 999,
              //   text: "登    录",
              //   color: Color.fromRGBO(23, 176, 91, 1),
              //   onTop: doLogin,
              // ),
            ],
          ),
        ),
      ),
    );
  }

  /// 保存登录用户列表增加的代码

  ///构建历史账号ListView
  Widget _buildListView() {
    double _line_height = 110;
    int _height = g_users.length * _line_height.toInt();
    if (_height > 550) {
      _height = 550;
    }
    if (g_can_expand_ListView) {
      return Center(
        child: Container(
          width: ScreenUtil().screenWidth * 0.9,
          // 模拟器：610越界，600刚好，550存放5个行刚好。S10，600越界
          height: ScreenUtil().setHeight(_height),
          decoration: BoxDecoration(
            border: Border(
              left: BorderSide(width: 1, color: Colors.black),
              right: BorderSide(width: 1, color: Colors.black),
              bottom: BorderSide(width: 1, color: Colors.black),
            ),
          ),
          // decoration: new BoxDecoration(
          //   border: new Border.all(color: Colors.black, width: 0.5),
          //   // color: Colors.black,
          //   // borderRadius: new BorderRadius.circular((20.0)),
          // ),
          child: ListView.builder(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            itemBuilder: (context, index) {
              UserAccount user = g_users[index];
              return GestureDetector(
                child: Column(
                  children: [
                    Container(
                      // height: ScreenUtil().setHeight(_line_height),
                      // color: Colors.grey[200],
                      color: Colors.grey[200],
                      // padding: EdgeInsets.only(left: 8, top: 4, right: 8, bottom: 4),
                      padding: EdgeInsets.symmetric(
                          horizontal: ScreenUtil().setHeight(35),
                          vertical: ScreenUtil().setHeight(17)),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text("${(index + 1).toString()}、${user.username}"),
                              GestureDetector(
                                child: Padding(
                                  padding: EdgeInsets.all(0),
                                  child: Icon(
                                    // Icons.remove_circle_outline,
                                    Icons.highlight_off,
                                    color: Colors.grey,
                                  ),
                                ),
                                onTap: () {
                                  setState(() {
                                    g_users.remove(user);
                                    SaveAccountPasswordManager.delUser(user);
                                    //处理最后一个数据，假如最后一个被删掉，将Expand置为false
                                    //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
                                    g_can_expand_ListView = g_users.isNotEmpty;
                                  });
                                },
                              ),
                            ],
                          ),
                          Divider(height: 1.0, color: Colors.black),
                        ],
                      ),
                    ),
                  ],
                ),
                onTap: () {
                  setState(() {
                    g_userInfo.username = user.username;
                    g_userInfo.password = user.password;
                    g_can_expand_ListView = false;
                  });
                },
              );
            },
            itemCount: g_users.length,
          ),
        ),
      );
    }
    return Container();
  }

  ///获取历史用户
  void _gainUsers() async {
    g_users.clear();
    g_users.addAll(await SaveAccountPasswordManager.getUsers());
    //默认加载第一个账号
    // if (g_users.isNotEmpty) {
    //   setState(() {
    //     g_userInfo.username = g_users[0].username;
    //     g_userInfo.password = g_users[0].password;
    //   });
    // }
  }
}
