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/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 SecurityPassword extends StatefulWidget {
  final Map<String, dynamic> model;

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

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

class _SecurityPasswordState extends State<SecurityPassword> {
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _confirmController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  int _second = 0;
  bool _canConfirm = false;
  String _phone;

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

    _passwordController.addListener(_verifiy);
    _confirmController.addListener(_verifiy);
    _codeController.addListener(_verifiy);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: _createNav(),
        body: Container(
          padding: EdgeInsets.only(top: 8),
          child: Column(
            children: <Widget>[
              SecurityBindInput(
                '新密码',
                '请输入需更改的密码',
                controller: _passwordController,
                obscureText: true,
              ),
              SecurityBindInput(
                '确认密码',
                '请确认新输入的密码',
                controller: _confirmController,
                obscureText: true,
              ),
              SecurityBindInput(
                '密保手机',
                _phone ?? '******',
                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());
                    _confirm();
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

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

  void _sendCode() async {
    NetUtil.request('/api/v1/settings/account/security/password/sms',
        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 _confirm() async {
    NetUtil.request('/api/v1/settings/account/security/password',
        params: Map<String, dynamic>.from({
          'new_password': _passwordController.text,
          'new_password_ack': _confirmController.text,
          'valid_code': _codeController.text,
        }),
        method: NetMethod.POST, onSuccess: (result) {
      Logger.debug(result);
      Fluttertoast.showToast(msg: '设置成功');
      Navigator.of(context).pop();
    });
  }
}
