import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/pages/login/login_widget.dart';
import 'package:sport/provider/login_info_model.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/button_cancel.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/misc.dart';

class BindPhoneDialog extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BindPhoneDialog();
  }
}

class _BindPhoneDialog extends State<BindPhoneDialog> {
  String _phone = "";
  String _code = "";
  FocusNode _codeFocus;
  Timer _timer;
  ValueNotifier<int> _seconds = ValueNotifier(0);

  @override
  void initState() {
    super.initState();
    _codeFocus = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    _codeFocus?.dispose();
    _cancelTimer();
  }

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

  void _startTimer() {
    _cancelTimer();
    _seconds.value = 60;
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面
      _seconds.value = _seconds.value - 1;
      if (_seconds.value <= 0) {
        setState(() {
          _cancelTimer();
        });
      }
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      elevation: 0,
      // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          color: Colors.white,
        ),
        child: Stack(
          children: <Widget>[
            SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  SizedBox(height: 30,),
                  Text(
                    "绑定号码",
                    style: Theme.of(context).textTheme.headline1,
                    strutStyle: fixedLine,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Input(
                          width: double.infinity,
                          labelText: "请输入手机号",
                          height: 35,
                          textInputType: TextInputType.phone,
                          maxLength: 11,
                          callBack: (value) {
                            _phone = value;
                            _phone = _phone.substring(0, min(11, _phone.length));
                          },
                        ),
                        Row(
                          children: <Widget>[
                            Expanded(
                              child: Input(
                                height: 35,
                                width: double.infinity,
                                focusNode: _codeFocus,
                                labelText: "请输入验证码",
                                textInputType: TextInputType.number,
                                maxLength: 4,
                                callBack: (value) {
                                  _code = value;
                                  _code = _code.substring(0, min(4, _code.length));
                                },
                              ),
                            ),
                            SizedBox(
                              width: 10,
                            ),
                            InkWell(
                                onTap: () async {
                                  if (_phone.length < 11) {
                                    ToastUtil.show("请输入正确的手机码号码");
                                    return;
                                  }
                                  if (_seconds.value > 0) return;

                                  final _loginInfoModel = LoginInfoModel();
                                  var code = await request(context, () async {
                                    return await _loginInfoModel.getCaptcha(_phone).catchError((err) {});
                                  });
                                  if (code == true) {
                                    _startTimer();
                                    _codeFocus.requestFocus();
                                  }
                                },
                                child: Container(
                                    width: 95,
                                    child: Center(
                                      child: _seconds.value > 0
                                          ? ValueListenableBuilder(
                                              valueListenable: _seconds,
                                              builder: (BuildContext context, int value, Widget child) => Text(
                                                "${value}s后重新获取",
                                                style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                              ),
                                            )
                                          : Text(
                                              "发送验证码",
                                              style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                            ),
                                    )))
                          ],
                        ),
                        SizedBox(
                          height: 6,
                        ),
                        Text(
                          "根据相关条约与法律法规，您需要进行手机号码绑定才可进行相关操作",
                          style: Theme.of(context).textTheme.bodyText1.copyWith(color: Color(0xffc2c2c2)),
                          strutStyle: StrutStyle(height: 1.4),
                        ),
                        SizedBox(
                          height: 16,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Expanded(
                              child: CancelButton(
                                  height: 35,
                                  callback: () {
                                    Navigator.of(context).pop(false);
                                  },
                                  content: "取消"),
                            ),
                            SizedBox(
                              width: 16,
                            ),
                            Expanded(
                              child: PrimaryButton(
                                  height: 35,
                                  callback: () async {
                                    final _loginInfoModel = LoginInfoModel();
                                    var result = await _loginInfoModel.loginApi.bindPhone(_phone, _code);
                                    if (result != null && result['code'] == 0) {
                                      _loginInfoModel.saveUserInfo({"phone": _phone});
                                      ToastUtil.show("绑定成功");
                                      Navigator.of(context).pop(true);
                                    }
                                  },
                                  content: "绑定"),
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Positioned(
              right: 0,top: 0,
                child: IconButton(
                  icon: Image.asset("lib/assets/img/btn_close_big.png"),
                  onPressed: () => Navigator.pop(context, false),
                )),
          ],
        ),
      ),
    );
  }
}

Future<bool> showBindPhoneDialog(BuildContext context) async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  bool result = (preferences.get("phone") ?? "").toString().length > 0 ;
  if (!result) {
    result = await showDialog(context: context, builder: (context) => BindPhoneDialog());
  }
  return result;
}
