import 'dart:convert';

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 LoginByName2 extends StatefulWidget {
  LoginByName2({Key key, this.height}) : super(key: key);
  double height;

  _LoginPageState createState() => _LoginPageState();
}

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

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

  bool bRemmberPW = false;

  @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);
    }
    try_setState();
  }

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

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

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

    // 一套APP适应多个区县登录过程02、进行登录验证，保存登录信息
    if (bRemmberPW) {
      Storage.setBool('bRemmberPW', bRemmberPW);
      //加密保存
      Storage.setString('username', EncryptUtil.aesEncode(g_userInfo.username));
      Storage.setString('password', EncryptUtil.aesEncode(g_userInfo.password));
    } else {
      Storage.remove('username');
      Storage.remove('password');
    }

    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}');

          // if (bRemmberPW) {
          //   // SaveAccountPasswordManager.getUsers();
          //   SaveAccountPasswordManager.saveUser(
          //       UserAccount(g_userInfo.username, g_userInfo.password));
          //   SaveAccountPasswordManager.getUsers().then((listUsers) {
          //     print("listUsers =\n${listUsers}");
          //   });
          // } else {
          //   SaveAccountPasswordManager.getUsers().then((listUsers) {
          //     // print("listUsers =\n${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: 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(380),
              padding: EdgeInsets.only(top: 10, bottom: 20, left: 20, right: 20),
              child: Column(
                children: <Widget>[
                  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),
                  ),
                  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),
                  ),
                ],
              ),
            ),
            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),
                ),
              ),
            ),
            // JdButton(
            //   height: 126,
            //   //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
            //   width: 999,
            //   text: "登    录",
            //   color: Color.fromRGBO(23, 176, 91, 1),
            //   onTop: doLogin,
            // ),
          ],
        ),
      ),
    );
  }
}
