import 'dart:async';
import 'package:dartin/dartin.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/bean/login.dart';
import 'package:sport/provider/login_info_model.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.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/loading.dart';

class AuthCodePage extends StatefulWidget {
  String _phone;
  AuthCodePage(this._phone);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AuthCodePageState();
  }
}

class _AuthCodePageState extends State<AuthCodePage> {
  Timer _timer;
  int _seconds;
  bool _isShowAuthCode;
  LoginInfoModel _loginInfoModel = inject();
  bool _isLoading;
  final spinkit = SpinKitDualRing(
    color: Colors.black,
    size: 200.0,
  );
  @override
  void initState() {
    super.initState(); //获取当期时间
    // var now = DateTime.now();
    // 获取 2 分钟的时间间隔
    // var twoHours = now.add(Duration(minutes: 2)).difference(now);
    //获取总秒数，2 分钟为 120 秒
    startTimer();
    _isShowAuthCode = false;
    _isLoading = false;
  }

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

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

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

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        leading: buildBackButton(context),
      ),
      body: Container(
        color: Colors.white,
        width: double.infinity,
        child: Column(
          children: <Widget>[
            // head
            Padding(
              padding: EdgeInsets.only(bottom: 20.0, top: 70.0),

              child: Text("输入验证码", style: TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontSize: 25.0, fontWeight: FontWeight.bold)),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 16.0),
              child: Text(
                "验证码已发送至 +${widget._phone}",
                style: TextStyle(
                    color: Color.fromRGBO(102, 102, 102, 1), fontSize: 14.0),
              ),
            ),
            Stack(
              children: <Widget>[
                _isLoading ? FadeingCircleLoading(context) : Container(),
                Padding(
                    padding:
                        EdgeInsets.symmetric(vertical: 16.0, horizontal: 70.0),
                    // onSumbit 是输入完的回调 判断一手
                    child: LcfarmCodeInput(
                      codeLength: 4,
                      onSubmit: (value) async {
                        setState(() {
                          _isLoading = true;
                        });
                        var flag = await _loginInfoModel.getlogin(
                            context, widget._phone,
                            captcha: "$value");
                        setState(() {
                          _isLoading = false;
                        });

                        if (flag) {
                          bool isNew = _loginInfoModel.isNew;
                          String username = _loginInfoModel.username;
                          print(isNew);
                          print(_loginInfoModel);
                          if (isNew) {
                            NavigatorUtil.goBasicInfo(context,
                                username: username);
                          } else {
                            NavigatorUtil.goHomePage(context);
                          }
                        }
                      },
                    )),
              ],
            ),
            SizedBox(height: 24.0,),
            PrimaryButton(
              width: 300,
              height: 44.0,content: _isShowAuthCode == false ? "$_seconds秒后重新获取验证码" : "重新获取验证码",callback: _isShowAuthCode == false ? null : () {
              if (_isShowAuthCode) {
//                  print("重新获取验证码");
                _loginInfoModel.getCaptcha(widget._phone).then((value) {
                  setState(() {
                    _isShowAuthCode = false;
                    startTimer();
                  });
                });
              }
            },),
          ],
        ),
      ),
    );
  }
}
