import 'dart:async';

import 'package:dartin/dartin.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sport/pages/login/login_widget.dart';
import 'package:sport/provider/login_info_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/code_input.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/space.dart';

class RestPasswordWidget extends StatefulWidget {
  final bool password;

  RestPasswordWidget(this.password);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _RestPasswordWidgetState();
  }
}

class _RestPasswordWidgetState extends State<RestPasswordWidget> {
  int _progress = 0; // 流程 1 2 3
  DateTime _lastPressed;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  setProgress({int progress}) {
    print(progress);
    setState(() {
      progress != null ? _progress = progress : _progress += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => _progress > 0
          ? showDialog(
              context: context,
              builder: (context) => CustomAlertDialog(
                    title: '你真的要退出吗',
                    ok: () {
                      Navigator.of(context).pop(true);
                    },
                  ))
          : true,
      child: Scaffold(
          backgroundColor: Colors.white,
          body: CustomScrollView(slivers: <Widget>[
            buildSliverAppBar(context, "重置密码"),
            SliverToBoxAdapter(
              child: Container(
                  color: Colors.white,
                  width: double.infinity,
                  alignment: Alignment.center,
                  child: Center(
                      child: Padding(
                    padding: const EdgeInsets.only(top: 32.0),
                    child: ConstrainedBox(
                        constraints: BoxConstraints(maxWidth: 300),
                        child: Column(
                          children: <Widget>[
                            ProgressWidget(widget.password, _progress, setProgress),
                          ],
                        )),
                  ))),
            )
          ])),
    );
  }
}

class ProgressWidget extends StatefulWidget {
  final bool password;
  int _progress;
  Function callback;

  ProgressWidget(this.password, this._progress, this.callback);

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

class _ProgressWidgetState extends State<ProgressWidget> {
  String _onePassword;
  String _twoPassword;
  String _phone;
  String _captcha;
  Timer _timer;
  int _seconds;
  bool _isShowAuthCode;
  LoginInfoModel _loginInfoModel = inject();
  String _oldPassword;
  String _newPassword;

  @override
  void initState() {
    super.initState();
    _seconds = widget._progress == 4 ? 60 : 3;
    _isShowAuthCode = false;
    startTimer();
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  void startTimer({int flag}) {
    //设置 1 秒回调一次
    cancelTimer();
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面
      setState(() {
        //秒数减一，因为一秒回调一次
        _seconds--;
        print(_seconds);
        if (_seconds <= 0) {
          //倒计时秒数为0，取消定时器
          cancelTimer();
          setState(() {
            _isShowAuthCode = true;
          });
          if (flag == 1) {
            NavigatorUtil.goLogin(context);
          }
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }

  @override
  Widget build(BuildContext context) {
    Widget _progressWidet0 = Column(
      children: <Widget>[
        if (widget.password == true)
          PrimaryButton(
            content: '通过密码',
            callback: () => widget.callback(progress: 5),
          ),
        if (widget.password == true)
          Space(
            height: 30.0,
          ),
        PrimaryButton(
          content: '通过手机',
          callback: () => widget.callback(),
        ),
      ],
    );

    Widget _progressWidget1 = Column(
      children: <Widget>[
        Container(
          width: 300.0,
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(bottom: 12.0, left: 10.0),
          child: Text(
            "请填写你要找回密码的手机号",
            style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 14.0),
          ),
        ),
        Input(
          labelText: "请输入手机号",
          textInputType: TextInputType.phone,
          maxLength: 11,
          callBack: (value) {
            setState(() {
              _phone = value; // String类型看着要不要强转
            });
          },
        ),
        SizedBox(
          height: 12,
        ),
        PrimaryButton(
          content: "下一步",
          callback: () async {
            bool flag = await _loginInfoModel.getCaptcha(_phone);
            // bool flag =true;
            if (flag) {
              widget.callback();
              setState(() {
                _seconds = 60;
                _isShowAuthCode = false;
              });
              startTimer();
            }
          },
        ),
      ],
    );

    Widget _progressWidget2 = Column(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(bottom: 32.0),
          child: Text(
            "正在向您帐号关联手机号码发送验证码",
            style: TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontWeight: FontWeight.w400),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 32.0),
          child: Text(
            "验证码已发送至$_phone",
            style: TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontWeight: FontWeight.w400),
          ),
        ),
        Padding(
            padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 70.0),
            // onSumbit 是输入完的回调 判断一手
            child: LcfarmCodeInput(
              codeLength: 4,
              onSubmit: (value) async {
                bool flag = await _loginInfoModel.verifyCaptch(_phone, value);
                setState(() {
                  _captcha = value;
                });
                if (flag) {
                  widget.callback();
                }
              },
            )),
        PrimaryButton(
          content: _isShowAuthCode == false ? "$_seconds秒后重新获取验证码" : "重新获取验证码",
          callback: _isShowAuthCode == false
              ? null
              : () async {
                  if (_isShowAuthCode) {
                    print("重新获取验证码");
                    bool flag = await _loginInfoModel.getCaptcha(_phone);
                    if (flag) {
                      setState(() {
                        _seconds = 60;
                        _isShowAuthCode = false;
                      });
                      startTimer();
                    }
                  }
                },
        ),
      ],
    );

    Widget _progressWidget3 = Column(
      children: <Widget>[
        Container(
            height: 44.0,
            width: 300.0,
            margin: EdgeInsets.only(bottom: 17.0),
            child: Container(
              padding: EdgeInsets.only(left: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    child: TextField(
//                      focusNode: _phone,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        labelText: "请输入新密码",
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                      ),
                      onChanged: (value) {
                        setState(() {
                          _onePassword = value;
                        });
                      },
                    ),
                  )
                ],
              ),
              decoration: BoxDecoration(border: Border.all(color: Color.fromRGBO(206, 206, 206, 1)), borderRadius: BorderRadius.all(Radius.circular(44.0))),
            )),
        Container(
            height: 44.0,
            width: 300.0,
            margin: EdgeInsets.only(bottom: 17.0),
            child: Container(
              padding: EdgeInsets.only(left: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    child: TextField(
//                      focusNode: _password,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        labelText: "再次确认密码",
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                      ),
                      onChanged: (value) {
                        setState(() {
                          _twoPassword = value;
                        });
                      },
                    ),
                  )
                ],
              ),
              decoration: BoxDecoration(border: Border.all(color: Color.fromRGBO(206, 206, 206, 1)), borderRadius: BorderRadius.all(Radius.circular(44.0))),
            )),
        PrimaryButton(
          content: '完成',
          callback: () async {
            if (_twoPassword != _onePassword) {
              ToastUtil.show("两次输入的密码不一致");
            } else {
              bool flag = await _loginInfoModel.resetPasswordByCaptcha(_phone, _captcha, _onePassword);
              setState(() {
                _seconds = 3;
                startTimer(flag: 1);
              });
              if (flag) widget.callback();
            }
          },
        ),
      ],
    );

    Widget _progressWidget4 = Column(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(bottom: 20.0),
          child: Image.asset(
            "lib/assets/img/pop_image_ok@.png",
            width: 80.0,
            height: 80.0,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 6.0),
          child: Text(
            "密码更换成功",
            style: TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontSize: 25.0),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 36.0),
          child: Text(
            "$_seconds秒后自动跳转至登陆界面",
            style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12.0),
          ),
        ),
        PrimaryButton(
          content: '立即跳转',
          callback: () {
            NavigatorUtil.goLogin(context);
          },
        ),
      ],
    );

    Widget _progressWidget5 = Column(
      children: <Widget>[
        Input(
          labelText: "请输入旧密码",
          callBack: (value) {
            setState(() {
              _oldPassword = value; // String类型看着要不要强转
            });
          },
          obscureText: true,
        ),
        Input(
          labelText: "请输入新密码",
          callBack: (value) {
            setState(() {
              _newPassword = value; // String类型看着要不要强转
            });
          },
          obscureText: true,
        ),
        Input(
          labelText: "确认新密码",
          callBack: (value) {
            setState(() {
              _twoPassword = value; // String类型看着要不要强转
            });
          },
          obscureText: true,
        ),
        Space(
          height: 30.0,
        ),
        PrimaryButton(
          content: '确定',
          callback: () async {
            if (_twoPassword != _newPassword) {
              ToastUtil.show("两次输入的密码不一致");
              return;
            }
            bool flag = await _loginInfoModel.resetPasswordByOld(_oldPassword, _newPassword);
            if (flag) {
              setState(() {
                _seconds = 3;
              });
              startTimer(flag: 1);
              widget.callback(progress: 4);
            }
          },
        ),
      ],
    );

    List<Widget> _progressWidget = [_progressWidet0, _progressWidget1, _progressWidget2, _progressWidget3, _progressWidget4, _progressWidget5];

    // TODO: implement build
    return _progressWidget[widget._progress];
  }
}
