import 'package:flutter/material.dart';
import '../../components/commonFun.dart';
import '../../widget/JdText.dart';
import '../../widget/JdButton.dart';

import '../../config/Config.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../services/Storage.dart';
import 'dart:convert';
import '../../components/EncryptUtil.dart';

import '../../services/EventBus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../config/service_url.dart';

class ModifyPassword extends StatefulWidget {
  ModifyPassword({Key key}) : super(key: key);

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<ModifyPassword> {
  //监听登录页面销毁的事件
  dispose() {
    super.dispose();
    eventBus.fire(new UserEvent('登录成功...'));
  }

  String oldPassword = '';
  String newPassword1 = '';
  String newPassword2 = '';

  doModifyPw() async {
    oldPassword = oldPassword.trim();
    newPassword1 = newPassword1.trim();
    newPassword2 = newPassword2.trim();

    RegExp regNewPw = RegExp(r"^[a-zA-Z0-9\?_!@#\$\%\^&]+$");
    if (g_userInfo.password.isNotEmpty && oldPassword != g_userInfo.password) {
      Fluttertoast.showToast(
        msg: '输入的旧密码错误！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    } else if (newPassword1 != newPassword2) {
      Fluttertoast.showToast(
        msg: '两次输入的新密码不一致！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    } else if (oldPassword == newPassword1) {
      Fluttertoast.showToast(
        msg: '新旧密码不能完全一样！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    } else if (newPassword1.length < 6 || newPassword1.length > 12) {
      Fluttertoast.showToast(
        msg: '新密码位数不对，应在 6-12 位之间！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    } else if (!regNewPw.hasMatch(newPassword1)) {
      Fluttertoast.showToast(
        msg: '新密码格式不对，应该由 6-12 位英文字母、数字和特殊符号组成！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    } else {
      doModifyPwDio().then((value) {
        if (value) {
          print(value);
          //密码修改成，保存新密码
          g_userInfo.password = newPassword1;
          //加密保存新密码
          Storage.setString('password', EncryptUtil.aesEncode(g_userInfo.password));

          Fluttertoast.showToast(
            msg: '密码修改成功！',
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.CENTER,
          );

          Navigator.pop(context); // 返回上一个页面
        }
      });
    }
  }

  Future doModifyPwDio() async {
    var api = ServicePath.modifyPwUrl;
    print(api);
    bool ret = false;

    try {
      print('开始处理修改密码请求...');
      print('username = ${g_userInfo.username}');
      print('password = ${g_userInfo.password}');
      Response response;
      Dio dio = Dio();

      String random = RandomBit(6); //flutter （dart）生成N位随机数
      response = await dio.post(api, data: {
        "username": g_userInfo.username,
        "oldpassword": oldPassword,
        "newpassword": newPassword1,
        "sign": GenerateMd5(APPkey + random),
        "random": random,
      });
      print('response = ${response.toString()}');
      //response = {"ret":200,"data":"密码修改成功","msg":""}
      //response = {"ret":200,"data":"原密码错误","msg":""}

      if (response.statusCode == 200) {
        if (response.data["data"].indexOf('成功') > 0) {
          ret = true;
          print('密码修改成功');
          print('response.data["data"] = ${response.data["data"]}');
        } else {
          print('密码修改失败：${response.data["data"]}！');
          Fluttertoast.showToast(
            msg: '密码修改失败：${response.data["data"]}！',
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.CENTER,
          );
        }
        print('密码修改过程正常完成');
      } else {
        throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
      }
    } catch (e) {
      print('密码修改过程异常...');
      print('ERROR:======>${e}');
      Fluttertoast.showToast(
        msg: 'ERROR:======>${e}',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }

    return ret;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
        // 设置appBar高度
        child: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          titleSpacing: 0.0,
          //设置title的左边距
          flexibleSpace: Container(
            //SizedBox(height: ScreenUtil().statusBarHeight), //显示顶部状态栏
            // SizedBox(height: ScreenUtil().setHeight(10)), //显示顶部状态栏
            padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight), //留出顶部状态栏高度
            child: Container(
              //height: ScreenUtil().setHeight(173),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color.fromRGBO(12, 186, 156, 1),
                    Color.fromRGBO(39, 127, 235, 1),
                  ],
                ),
              ),
              // decoration: BoxDecoration(
              //   gradient: LinearGradient(colors: [
              //     Color(0xFF0018EB),
              //     Color(0xFF01C1D9),
              //   ], begin: Alignment.bottomCenter, end: Alignment.topCenter),
              // ),
            ),
          ),
          title: Padding(
            padding: EdgeInsets.only(left: 0, right: 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                getIconAndTextButton(
                  iconColor: Colors.white,
                  iconData: Icons.chevron_left_outlined,
                  onPress: () {
                    Navigator.pop(context);
                  },
                ),
                Expanded(
                  child: Text("修改密码",
                      style: TextStyle(color: Colors.white, fontSize: 20),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis),
                ),
                SizedBox(width: 50),
              ],
            ),
          ),
        ),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 30, bottom: 20, left: 20, right: 20),
        child: ListView(
          children: <Widget>[
            Center(
              child: Container(
                margin: EdgeInsets.only(top: 30),
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(160),
                //child: Image.asset('assets/images/user.png', fit: BoxFit.cover),
                child: Image.asset('assets/images/ybsthbj.png', fit: BoxFit.fitHeight),
                // child: Image.network(
                //     'https://www.itying.com/images/flutter/list5.jpg',
                //     fit: BoxFit.cover),
              ),
            ),
            SizedBox(height: 50),
            JdText(
              height: ScreenUtil().setHeight(300),
              title: '旧密码：',
              text: "请输入旧密码",
              password: true,
              onChanged: (String value) {
                // print(value);
                oldPassword = value;
              },
              endBtn: 'ShowHiddenBtn',
            ),
            SizedBox(height: 20),
            JdText(
              height: ScreenUtil().setHeight(300),
              title: '新密码：',
              text: "请输入6-12位新密码",
              password: true,
              onChanged: (String value) {
                // print(value);
                newPassword1 = value;
              },
              endBtn: 'ShowHiddenBtn',
            ),
            SizedBox(height: 20),
            JdText(
              height: ScreenUtil().setHeight(300),
              title: '新密码：',
              text: "请再次输入6-12位新密码",
              password: true,
              onChanged: (String value) {
                // print(value);
                newPassword2 = value;
              },
              endBtn: 'ShowHiddenBtn',
            ),
            SizedBox(height: 20),
            Container(
              alignment: Alignment(0, 0),
              height: ScreenUtil().setHeight(222),
              //width: ScreenUtil().setWidth(142),
              padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(25), right: ScreenUtil().setWidth(25)),
              decoration: new BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                border: new Border.all(width: 1, color: Colors.grey),
              ),
              child: Text('新密码需要6-12位，可以由大小写字母、阿拉伯数字，以及英文 ?、_、！、@、#、\$、%、^、& 等字符组成。',
                  style: TextStyle(fontSize: 15)),
            ),
            SizedBox(height: 60),
            JdButton(
              height: ScreenUtil().setHeight(382),
              //height: 126,
              text: "确认",
              color: Colors.blueAccent,
              onTop: doModifyPw,
            )
          ],
        ),
      ),
    );
  }
}
