import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_base_widget/pages/security_page/security_bind_alipay/models/security_bind_alipay_model.dart';
import 'package:zhiying_base_widget/pages/security_page/security_bind_alipay/security_bind_alipay_bloc.dart';
import 'package:zhiying_base_widget/pages/security_page/security_unbind_alipay/security_unbin_alipay.dart';
import 'package:zhiying_base_widget/pages/security_page/widgets/security_bind_input.dart';
import 'package:zhiying_base_widget/pages/security_page/widgets/security_code_button.dart';
import 'package:zhiying_base_widget/pages/security_page/widgets/security_confirm_button.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

// 绑定支付宝
class SecurityBindAlipayPage extends StatefulWidget {
  final Map<String, dynamic> model;

  const SecurityBindAlipayPage(this.model, {Key key}) : super(key: key);

  @override
  _SecurityBindAlipayPageState createState() => _SecurityBindAlipayPageState();
}

class _SecurityBindAlipayPageState extends State<SecurityBindAlipayPage> {
  @override
  Widget build(BuildContext context) {
    Logger.debug(widget.model.toString());
    Map<String, dynamic> status = widget.model['status'];
    Map<String, dynamic> datas = widget.model['data'];
    if (status['alipay_setting'] == '1') {
      return SecurityUnbinAlipay(widget.model);
    } else {
      return BlocProvider<SecurityBindAlipayBloc>(
        bloc: SecurityBindAlipayBloc(),
        child: _SecurityBindAlipayContainer(datas),
      );
    }
  }
}

class _SecurityBindAlipayContainer extends StatefulWidget {
  final Map<String, dynamic> model;

  const _SecurityBindAlipayContainer(this.model, {Key key}) : super(key: key);

  @override
  _SecurityBindAlipayContainerState createState() =>
      _SecurityBindAlipayContainerState();
}

class _SecurityBindAlipayContainerState
    extends State<_SecurityBindAlipayContainer> {
  SecurityBindAlipayBloc _bloc;
  SecurityBindAlipayModel _model;

  TextEditingController _nameController = TextEditingController();
  TextEditingController _accountController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  int _second = 0;
  bool _canConfirm = false;

  @override
  void initState() {
    _bloc = BlocProvider.of<SecurityBindAlipayBloc>(context);
    _bloc.loadData(widget.model['skip_identifier'].toString());

    _nameController.addListener(_verifiy);
    _accountController.addListener(_verifiy);
    _codeController.addListener(_verifiy);

    super.initState();
  }

  void _verifiy() {
    bool canConfirm = _nameController.text.length > 0 &&
        _accountController.text.length > 0 &&
        _codeController.text.length == 6;
    if (canConfirm != _canConfirm) {
      setState(() {
        _canConfirm = canConfirm;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<SecurityBindAlipayModel>(
      stream: _bloc.outData,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        _model = snapshot.data;
        return GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Scaffold(
            appBar: _createNav(),
            body: Padding(
              padding: const EdgeInsets.only(top: 5),
              child: _model == null
                  ? Container()
                  : Column(
                      children: <Widget>[
                        SecurityBindInput(
                          '真实姓名',
                          '请输入支付宝认证的真实姓名',
                          controller: _nameController,
                        ),
                        SecurityBindInput(
                          '支付宝号',
                          '请输入要绑定的支付宝账号',
                          controller: _accountController,
                        ),
                        SecurityBindInput(
                          '验证码',
                          '请输入验证码',
                          controller: _codeController,
                          rightWidget: SecurityCodeButton(
                            _second <= 0 ? '获取验证码' : '${_second.toString()}s',
                            enabled: _second <= 0,
                            onSend: () {
                              _sendCode();
                              Logger.debug('发送验证码');
                            },
                          ),
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(6)
                          ],
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 8),
                          child: SecurityConfirmButton(
                            text: '确定',
                            enabled: _canConfirm,
                            onClick: () async {
                              Logger.debug('确定');
                              FocusScope.of(context).requestFocus(FocusNode());
                              if (await _bloc.bindAlipay(
                                  _nameController.text,
                                  _accountController.text,
                                  _codeController.text)) {
                                Fluttertoast.showToast(msg: '绑定成功');
                                Navigator.of(context).pop(true);
                              }
                            },
                          ),
                        ),
                      ],
                    ),
            ),
          ),
        );
      },
    );
  }

  // 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: HexColor.fromHex('#ffffff'),
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        '绑定支付宝',
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex('#333333'),
        ),
      ),
    );
  }

  void _sendCode() async {
    NetUtil.request('/api/v1/settings/account/security/alipay/sms',
        onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '发送成功');
      _second = 60;
      Timer.periodic(Duration(seconds: 1), (timer) {
        _second--;
        if (_second <= 0) {
          timer.cancel();
        }
        setState(() {});
      });
    });
  }
}
