import 'dart:async';

import 'package:dartin/dartin.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.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/widgets/appbar.dart';
import 'package:sport/widgets/code_input.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/button_primary.dart';

class FindPasswordPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FindPasswordPageState();
  }
}

class _FindPasswordPageState extends State<FindPasswordPage> {
  int _progress; // 流程 1 2 3
  DateTime _lastPressed;

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

  setProgress({int progress}) {
    setState(() {
      _progress += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    print(_progress);
    // TODO: implement build
    return Scaffold(
        body: WillPopScope(
          onWillPop: () async => _progress > 0
              ? showDialog(
                  context: context,
                  builder: (context) => CustomAlertDialog(
                        title: '你真的要退出吗',
                        ok: () {
                          Navigator.of(context).pop(true);
                        },
                      ))
              : true,
          child: CustomScrollView(slivers: <Widget>[
            SliverAppBar(
              pinned: true,
              elevation: 0,
              leading: buildBackButton(context),
              expandedHeight: 140.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text(
                  "找回密码",
                  style: titleStyle,
                ),
              ),
            ),
            SliverFillRemaining(
                hasScrollBody: false,
                fillOverscroll: false,
                child: Container(
                  color: Colors.white,
                  width: double.infinity,
                  padding: EdgeInsets.only(top: 20.0),
                  child: ProgressWidget(_progress, setProgress),
                )),
          ]),
        ));
  }
}

class ProgressWidget extends StatefulWidget {
  int _progress;
  Function callback;

  ProgressWidget(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();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget._progress);
    _seconds = widget._progress == 1 ? 60 : 3;
//    _phone = "+86 132 4228 9710";
    _isShowAuthCode = false;
    startTimer();
  }

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

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

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

  @override
  Widget build(BuildContext context) {
    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,
        ),
        Padding(
          padding: const EdgeInsets.only(bottom: 32.0),
          child: PrimaryButton(
            width: 300,
            content: "下一步",
            callback: () async {
              bool flag = await _loginInfoModel.getCaptcha(_phone);
              if (flag) {
                widget.callback();
              }
            },
          ),
        ),
      ],
    );

    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();
                }
              },
            )),
        InkWell(
          child: Container(
            width: 300,
            height: 44.0,
            alignment: Alignment.center,
            decoration: _isShowAuthCode == true
                ? BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(44.0)),
                    gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                      Color.fromRGBO(255, 196, 0, 1),
                      Color.fromRGBO(255, 170, 0, 1),
                    ]))
                : BoxDecoration(
                    color: Color.fromRGBO(153, 153, 153, 1),
                    borderRadius: BorderRadius.all(Radius.circular(44.0)),
                  ),
            child: Text(
              _isShowAuthCode == false ? "$_seconds秒后重新获取验证码" : "重新获取验证码",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          onTap: () {
            if (_isShowAuthCode) {
              print("重新获取验证码");
            }
          },
        ),
      ],
    );

    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))),
            )),
        InkWell(
          child: Container(
            width: 300,
            height: 44.0,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(44.0)),
                gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                  Color.fromRGBO(255, 196, 0, 1),
                  Color.fromRGBO(255, 170, 0, 1),
                ])),
            child: Text(
              "完成",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          onTap: () async {
            if (_twoPassword != _onePassword) {
              Fluttertoast.showToast(
                  msg: "两次输入的密码不一致",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.CENTER,
                  backgroundColor: Colors.white,
                  textColor: Colors.black,
                  fontSize: 13.0);
            } 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),
          ),
        ),
        InkWell(
          child: Container(
            width: 200,
            height: 32.0,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(44.0)),
                gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                  Color.fromRGBO(255, 196, 0, 1),
                  Color.fromRGBO(255, 170, 0, 1),
                ])),
            child: Text(
              "立即跳转",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          onTap: () {
            NavigatorUtil.goLogin(context);
          },
        ),
      ],
    );

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

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