import 'package:account_center/common/res/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class HintText extends StatefulWidget {
  final TextEditingController _pwdWordController;
  final String _hintText;
  final int maxLength; //最大输入长度
  final double hintSize; //提示文字尺寸
  final FocusNode focusNode;
  final Function(int)? callBack; //回调输入的字符数
  final List<TextInputFormatter>? inputFormatter;
  final bool isPass;

  final TextInputType keyboardType;

  const HintText(
    this._pwdWordController,
    this._hintText, {
    super.key,
    this.maxLength = 12,
    this.hintSize = 14.0,
    required this.focusNode,
    this.callBack,
    this.inputFormatter,
    this.isPass = false,
    this.keyboardType = TextInputType.text,
  });

  @override
  State<HintText> createState() => _HintTextState();
}

class _HintTextState extends State<HintText> {
  var _isShowPwd = false;

  // 监听焦点
  Future<void> _focusNodeListener() async {
    widget.focusNode.addListener(() {
      if (widget.focusNode.hasFocus) {
      } else {}
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    widget.focusNode.removeListener(_focusNodeListener);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _focusNodeListener();
    widget._pwdWordController.addListener(() {
      if (widget._pwdWordController.text.isNotEmpty) {
        widget.callBack?.call(widget._pwdWordController.value.text.length);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      maxLength: widget.maxLength,
      focusNode: widget.focusNode,
      controller: widget._pwdWordController,
      textAlignVertical: TextAlignVertical.center,
      inputFormatters: widget.inputFormatter,
      keyboardType: widget.keyboardType,
      decoration: InputDecoration(
        border: InputBorder.none,
        hintText: widget._hintText,
        counterText: "",
        hintStyle: TextStyle(
          color: Colors.grey.shade400,
          fontSize: widget.hintSize,
          fontWeight: FontWeight.w400,
        ),
        suffixIcon: (widget.isPass)
            ? IconButton(
                icon: Icon(
                  (_isShowPwd) ? Icons.visibility : Icons.visibility_off,
                  color: RColors.appMain,
                ),
                onPressed: () {
                  setState(() {
                    _isShowPwd = !_isShowPwd;
                  });
                },
              )
            : null,
        // 是否显示密码
      ),
      obscureText: !_isShowPwd && widget.isPass,
    );
  }
}
