import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/text_field.dart';
import 'package:oktoast/oktoast.dart';

class RegisterPage extends StatefulWidget {

  RegisterPage({this.authCode});

  final String authCode;

  @override
  State<StatefulWidget> createState() {
    return _RegisterState();
  }
}

class _RegisterState extends State<RegisterPage> {
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _vCodeController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _repasswordController = TextEditingController();
  TextEditingController _nicknameController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();
  final FocusNode _nodeText4 = FocusNode();
  final FocusNode _nodeText5 = FocusNode();
  bool _isClick = false;

  @override
  void initState() {
    super.initState();
    //监听输入改变
    _phoneController.addListener(_verify);
    _vCodeController.addListener(_verify);
    _passwordController.addListener(_verify);
    _repasswordController.addListener(_verify);
    _nicknameController.addListener(_verify);
  }

  void _verify() {
    String phone = _phoneController.text;
    String vCode = _vCodeController.text;
    String password = _passwordController.text;
    String repassword = _repasswordController.text;
    String nickname = _nicknameController.text;
    bool isClick = true;
    if (phone.isEmpty || phone.length < 11) {
      isClick = false;
    }
    if (vCode.isEmpty || vCode.length < 6) {
      isClick = false;
    }
    if (password.isEmpty || password.length > 16) {
      isClick = false;
    }
    if (repassword.isEmpty || repassword.length > 16) {
      isClick = false;
    }
    if (nickname.isEmpty || nickname.length == 0) {
      isClick = false;
    }
    print("_isClick${_isClick}");
    if (isClick != _isClick) {
      setState(() {
        _isClick = isClick;
      });
    }
  }

  void _register() {
    String phone = _phoneController.text;
    String password = _passwordController.text;
    String nickname = _nicknameController.text;
    String vCode = _vCodeController.text;
    showLoading(context,"正在执行...");
    ApiService(context: context).register(
        phone, Utils.generateMd5(password), nickname, vCode,widget.authCode,
        onSuccess: (data) {
          dismissLoading(context);
          showAlert(context, "提示", "注册成功,请登录", "确定", (){
            NavigatorUtils.goBack(context);
            NavigatorUtils.goBack(context);
          });
        }, onError: (code, msg) {
          dismissLoading(context);
          toasts(msg);
    });
  }

  Future<bool> _getVCode() async {
    await ApiService(context: context).getVCode(_phoneController.text.toString().trim(),
        onSuccess: (data) {
      print("成功");
    }, onError: (code, msg) {
          showToast(msg);
    });
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeUtils.getTabsBg(context),
        appBar: const MyAppBar(
          centerTitle: "注册",
        ),
        body: defaultTargetPlatform == TargetPlatform.iOS
            ? FormKeyboardActions(
                child: _buildBody(),
              )
            : SingleChildScrollView(
                child: _buildBody(),
              ));
  }

  _buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 34.0, right: 34.0, top: 20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Gaps.vGap16,
          MyTextField(
            key: const Key('phone'),
            focusNode: _nodeText1,
            config: Utils.getKeyboardActionsConfig(context,
                [_nodeText1, _nodeText2, _nodeText3, _nodeText4, _nodeText5]),
            controller: _phoneController,
            maxLength: 11,
            keyboardType: TextInputType.phone,
            hintText: "请输入手机号",
          ),
          Gaps.vGap8,
          MyTextField(
            key: const Key('vcode'),
            focusNode: _nodeText2,
            controller: _vCodeController,
            keyboardType: TextInputType.number,
            getVCode: () async {
              if (_phoneController.text.toString().trim().length == 11) {
                return await _getVCode();
              } else {
                toasts("请输入有效的手机号");
                return false;
              }
            },
            maxLength: 6,
            hintText: "请输入验证码",
          ),
          Gaps.vGap8,
          MyTextField(
            key: const Key('password'),
            keyName: 'password',
            focusNode: _nodeText3,
            isInputPwd: true,
            controller: _passwordController,
            keyboardType: TextInputType.visiblePassword,
            maxLength: 16,
            hintText: "请输入登录密码",
          ),
          Gaps.vGap8,
          MyTextField(
            key: const Key('repassword'),
            keyName: 'repassword',
            focusNode: _nodeText4,
            isInputPwd: true,
            controller: _repasswordController,
            keyboardType: TextInputType.visiblePassword,
            maxLength: 16,
            hintText: "确认登录密码",
          ),
          Gaps.vGap8,
          TextField(
            key: const Key('nickname'),
            maxLength: 10,
            controller: _nicknameController,
            focusNode: _nodeText5,
            keyboardType: TextInputType.text,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.only(bottom: 8.0),
              hintStyle: TextStyle(
                  fontSize: Dimens.font_sp14,
                  fontWeight: FontWeight.normal,
                  color: Colours.text_gray_c
              ),
              hintText: "请输入真实姓名",
              counterText: "",
              border: InputBorder.none,
                focusedBorder: UnderlineInputBorder(
                    borderSide:
                    BorderSide(color: Colours.text_gray_c, width: 0.8)),
                enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).dividerTheme.color,
                        width: 0.8))
            ),
          ),
          Gaps.vGap35,
          MyButton(
            key: const Key('register'),
            colors:
                _isClick ? null : [Colours.text_gray_c, Colours.text_gray_c],
            onPressed: _isClick ? _register : null,
            text: "注册",
          )
        ],
      ),
    );
  }
}
