import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/pages/login/login_widget.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/loading.dart';

class RegisterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _RegiseterState();
  }
}

class _RegiseterState extends State<RegisterPage> with InjectLoginApi {
  String _phone; // 手机号码
  String _authCode; // 状态码
  String _password; // 密码
  int _errStatus; // 错误状态 1:两次密码写错 2:手机号码已经被注册 3：
  FocusNode _focus1 = FocusNode();
  FocusNode _passwordFocus = FocusNode(); // 第二次密码
  String _pass;
  bool _isLoading = false;

  Timer _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = 29;

  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _codeCountdownStr = '${_countdownNum--}重新获取';
      _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '${_countdownNum--}重新获取';
          } else {
            _codeCountdownStr = '获取验证码';
            _countdownNum = 29;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  final spinkit = SpinKitDualRing(
    color: Colors.black,
    size: 200.0,
  );

  @override
  void initState() {
    super.initState();
    _errStatus = 0;
    checkPassword();
  }

  @override
  void dispose() {
    super.dispose();
    _focus1.dispose();
    _passwordFocus.dispose();
    _countdownTimer?.cancel();
    _countdownTimer = null;
  } // password check

  checkPassword() {
    _passwordFocus.addListener(() {
      if (!_passwordFocus.hasFocus) {
        // TextField has lost focus
        if (_password != _pass) {
          setState(() {
            _errStatus = 1;
          });
        } else {
          setState(() {
            _errStatus = 0;
          });
        }
      }
    });
  }

  Widget _getTips() {
    if (_errStatus == 1) {
      return Text(
        "两次输入的密码不同",
        style: TextStyle(color: Colors.red, fontSize: 12.0),
        textAlign: TextAlign.left,
      );
    } else if (_errStatus == 2) {
      return Text(
        "手机号码已经被注册了",
        style: TextStyle(color: Colors.red, fontSize: 12.0),
        textAlign: TextAlign.left,
      );
    } else {
      return Text("");
    }
  }

  Future<bool> myToast(String msg) {
    return Fluttertoast.showToast(
      msg: "$msg",
      backgroundColor: Colors.black,
      textColor: Colors.white,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: LoadingWidget(
            loading: _isLoading,
            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: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Input(
                            labelText: "请输入手机号",
                            textInputType: TextInputType.phone,
                            maxLength: 11,
                            callBack: (value) {
                              setState(() {
                                _phone = value; // String类型看着要不要强转
                              });
                            },
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Input(
                                labelText: "请输入验证码",
                                maxLength: 4,
                                width: 220.0,
                                focusNode: _focus1,
                                textInputType: TextInputType.number,
                                callBack: (value) {
                                  setState(() {
                                    _authCode = value; // String类型看着要不要强转
                                  });
                                },
                              ),
                              InkWell(
                                child: Container(
                                  padding: EdgeInsets.only(left: 10.0),
                                  child: Text(
                                    _countdownTimer == null ? "发送验证码" : "$_countdownNum秒后重试",
                                    style: TextStyle(color: Theme.of(context).accentColor),
                                  ),
                                ),
                                onTap: () {
                                  if (_countdownTimer != null) {
                                    return;
                                  }
                                  if (_phone == null) {
                                    myToast("请输入电话号码");
                                    return;
                                  }
                                  RegExp exp = RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$');
                                  bool matched = exp.hasMatch(_phone);
                                  if (!matched) {
                                    myToast("请输入正确的电话号码");
                                    return;
                                  }

                                  setState(() {
                                    _isLoading = true;
                                  });

                                  loginApi.getCaptcha(_phone).then((value) {
//                      print(value);
                                    if (value['code'] == 0) {
                                      myToast("验证码已经发送");
                                      FocusScope.of(context).requestFocus(_focus1);
                                      reGetCountdown();
                                    }
                                  }).whenComplete(() => setState(() {
                                        _isLoading = false;
                                      }));
                                },
                              ),
                            ],
                          ),
                          Input(
                            labelText: "请输入密码",
                            maxLength: 32,
                            textInputAction: TextInputAction.next,
                            callBack: (value) {
                              setState(() {
                                _password = value; // String类型看着要不要强转
                              });
                            },
                            obscureText: true,
                          ),
                          Input(
                            labelText: "再次确认密码",
                            maxLength: 32,
                            focusNode: _passwordFocus,
                            callBack: (value) {
                              setState(() {
                                _pass = value; // String类型看着要不要强转
                              });
                            },
                            obscureText: true,
                          ),
                          Container(width: 300.0, alignment: Alignment.centerLeft, padding: EdgeInsets.only(bottom: 14.0), child: _getTips()),
                          button("注册", () {
                            setState(() {
                              _isLoading = true;
                            });
                            loginApi.registerByPhone(_phone, _password, _authCode).then((value) async {
                             if (value['code'] == 0) {
                                setState(() {
                                  _isLoading = false;
                                });
                                SharedPreferences prefs = await SharedPreferences.getInstance();
                                prefs.setString("token", value['data']['token']);
                                prefs.setString("avatar", value['data']['user']['avatar']);
                                prefs.setString("name", value['data']['user']['name']);
                                Provider.of<UserModel>(context, listen: false).initUser();
                                NavigatorUtil.goBasicInfo(context);
                              }
                            }).whenComplete(() => setState(() {
                              _isLoading = false;
                            }));
                          })
                        ],
                      ),
                    )),
              ],
            )));
  }
}
