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_unbind.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 SecurityMobile extends StatefulWidget {
  final Map<String, dynamic> model;

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

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

class _SecurityMobileState extends State<SecurityMobile> {
  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> status = widget.model['status'];
    if (status['mobile_setting'] == '1') {
      return SecurityMobileUnbind(widget.model);
    } else {
      return _SecurityMobileContainer(widget.model);
    }
  }
}

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

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

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

class _SecurityMobileContainerState extends State<_SecurityMobileContainer> {
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  int _second = 0;
  bool _canConfirm = false;
  String _phone;
  String _unbindCode = '';

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

    _phoneController.addListener(_verifiy);
    _codeController.addListener(_verifiy);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createNav(),
      body: Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: Column(
          children: <Widget>[
            _unbindCode == null || _unbindCode == ''
                ? Container()
                : 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(
              '手机号',
              '请输入要绑定的手机号',
              keyboardType: TextInputType.number,
              controller: _phoneController,
            ),
            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());
                  _updatePhone();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  void _sendCode() async {
    NetUtil.request('/api/v1/settings/account/security/mobile/sms',
        params: Map<String, dynamic>.from({
          'mobile': _phoneController.text,
        }),
        method: NetMethod.POST, onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '发送成功');
      _second = 60;
      Timer.periodic(Duration(seconds: 1), (timer) {
        _second--;
        if (_second <= 0) {
          timer.cancel();
        }
        setState(() {});
      });
    });
  }

  // 设置手机号，没有手机号的调这个😵
  void _setPhone() async {
    NetUtil.request('/api/v1/settings/account/security/mobile',
        params: Map<String, dynamic>.from({
          'mobile': _phoneController.text,
          'valid_code': _codeController.text,
        }),
        method: NetMethod.POST, onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '设置成功');
      Navigator.of(context).pop();
    });
  }

  // 更新手机号，有手机号的调这个
  void _updatePhone() async {
    NetUtil.request('/api/v1/settings/account/security/mobile/unbind/update',
        params: Map<String, dynamic>.from({
          'mobile': _phoneController.text,
          'valid_code': _codeController.text,
        }),
        method: NetMethod.POST, onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '设置成功');
      Navigator.of(context).pop();
    });
  }
}
