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_mobile/security_mobile.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';

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

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

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

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

  @override
  void initState() {
    Logger.debug(widget.model.toString());
    Map<String, dynamic> status = widget.model['status'];
    _phone = status['mobile_setting_text'];
    _status = widget.model['status'];
    _codeController.addListener(_verifiy);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createNav(),
      body: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            padding:
                EdgeInsets.only(left: 12.5, right: 12.5, top: 10, bottom: 10),
            child: Text(
              '为了您的账户安全，将对原有手机号进行验证',
              style: TextStyle(fontSize: 12, color: Color(0xff999999)),
            ),
          ),
          SecurityBindInput(
            '验证原手机号',
            _phone ?? '******',
            keyboardType: TextInputType.number,
            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();
              },
            ),
          ),
        ],
      ),
    );
  }

  // 导航栏
  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 _verifiy() {
    bool canConfirm = _codeController.text.length == 6;
    if (canConfirm != _canConfirm) {
      setState(() {
        _canConfirm = canConfirm;
      });
    }
  }

  void _sendCode() async {
    NetUtil.request('/api/v1/settings/account/security/mobile/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(() {});
      });
    });
  }

  // 解绑手机号
  void _unbind() async {
    NetUtil.request('/api/v1/settings/account/security/mobile/unbind',
        params: Map<String, dynamic>.from({
          'valid_code': _codeController.text,
        }),
        method: NetMethod.POST, onSuccess: (result) {
      _status['mobile_setting'] = '0';
      _status['code'] = _codeController.text;
      Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => SecurityMobile(widget.model)));
    });
  }
}
