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/security_bind_alipay_page.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/zhiying_comm.dart';
import 'package:zhiying_comm/util/mob_util/mob_util.dart';

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

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

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

class _SecurityUnbinAlipayState extends State<SecurityUnbinAlipay> {
  TextEditingController _codeController = TextEditingController();
  Map<String, dynamic> _status;
  int _second = 0;
  bool _canConfirm = false;

  @override
  void initState() {
    Logger.debug(widget.model.toString());

    _status = widget.model['status'];
    _codeController.addListener(_verifiy);
    super.initState();
  }

  void _verifiy() {
    bool canConfirm = _codeController.text.length == 6;
    if (canConfirm != _canConfirm) {
      setState(() {
        _canConfirm = canConfirm;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Scaffold(
        appBar: _createNav(),
        body: Column(
          children: <Widget>[
            SecurityBindInput(
              '验证手机号',
              _status['mobile_setting_text'] ?? '',
              enabled: false,
            ),
            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());
                  _unbind();
                },
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
    );
  }

  // 导航栏
  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',
    //     method: NetMethod.GET, onSuccess: (result) {
    //   Logger.debug(result);
    //   Fluttertoast.showToast(msg: '发送成功');
    //   _second = 60;
    //   Timer.periodic(Duration(seconds: 1), (timer) {
    //     _second--;
    //     if (_second <= 0) {
    //       timer.cancel();
    //     }
    //     setState(() {});
    //   });
    // });

    bool result = await MobUtil.getTextCode(_status['mobile_setting_text'], smsCodeType: SMSCodeType.BIND_ALIPAY);
    if (result) {
      Fluttertoast.showToast(msg: '发送成功');
      _second = 60;
      Timer.periodic(Duration(seconds: 1), (timer) {
        _second--;
        if (_second <= 0) {
          timer.cancel();
        }
        setState(() {});
      });
    } else {
      // Fluttertoast.showToast(msg: '获取验证码失败');
    }
  }

  void _unbind() async {
    NetUtil.request('/api/v1/settings/account/security/alipay/unbind',
        params: Map<String, dynamic>.from({
          'valid_code': _codeController.text,
          'phone': _status['mobile_setting_text'],
          'zone': '86',
        }),
        method: NetMethod.POST, onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '解绑成功');
      _status['alipay_setting'] = '0';
      Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (context) => SecurityBindAlipayPage(widget.model)));
    });
  }
}
