import 'dart:async';
import 'package:flutter/material.dart';
import 'package:twong/utils/index.dart';

class CounterButton extends StatefulWidget {
  final int max;
  final String before;
  final String loading;
  final Function onClick;
  final Color color;
  final Color disableColor;
  CounterButton({ this.max = 60, this.before = "获取验证码", this.onClick,
    this.loading = " s 后可重新获取", this.color = Colors.white,
    this.disableColor = Colors.white });
  @override
  State<StatefulWidget> createState() {
    return _CounterButtonState();
  }
}

class _CounterButtonState extends State<CounterButton> {
  var _counter;
  Timer _timer;
  String _codeTxt;
  var _enable = true;

  @override
  void initState() {
    super.initState();
    _codeTxt = widget.before;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 38.px,
      width: 128.px,
      margin: EdgeInsets.only(bottom: 12.px),
      child: FlatButton(
        color: widget.color,
        child: Text(_codeTxt),
        shape: StadiumBorder(),
        disabledColor: widget.disableColor,
        onPressed: _enable ? _getCountdown : null,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if(_timer != null) {
      _timer.cancel();
    }
  }

  void _getCountdown() {
    if(widget.onClick != null) {
      var ret = widget.onClick();
      if(ret != null && !ret) {
        return;
      }
    }

    setState(() {
      _enable = false;
      _counter = widget.max;
      _codeTxt = "$_counter${widget.loading}";
    });

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_counter > 0) {
          _counter --;
          setState(() {
            _codeTxt = "$_counter${widget.loading}";
          });
        } else {
          _counter = widget.max;
          timer.cancel();
          setState(() {
            _enable = true;
            _codeTxt = "获取验证码";
          });
        }
      });
    });
  }
}