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

//带删除按钮的输入框
class ClearText extends StatefulWidget {
  final TextEditingController _mController; //控制器
  final String _hintText; //提示文字
  final int maxLength; //最大输入长度
  final double hintSize; //提示文字尺寸
  final String regExp; //正则表达式规则
  final FocusNode focusNode; //监听器
  final Function(int)? callBack; //回调输入的字符数
  final TextInputType inputType; //输入类型

  const ClearText(this._mController, this._hintText,
      {super.key,
      this.maxLength = 11,
      this.hintSize = 14.0,
      this.regExp = r'\d+',
      required this.focusNode,
      this.callBack,
      this.inputType = TextInputType.number});

  @override
  State<ClearText> createState() => _ClearTextState();
}

class _ClearTextState extends State<ClearText> {
  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  bool? _isShowUserClear = false;

  // 监听焦点
  _focusNodeListener() {
    setState(() {
      _isShowUserClear = widget.focusNode.hasFocus;
    });
  }

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

  @override
  void initState() {
    super.initState();
    widget.focusNode.addListener(_focusNodeListener);
    widget._mController.addListener(() {
      if (widget._mController.text.isNotEmpty && widget.callBack != null) {
        widget.callBack!(widget._mController.value.text.length);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      inputFormatters: [
        LengthLimitingTextInputFormatter(widget.maxLength),
        FilteringTextInputFormatter.allow(RegExp(widget.regExp))
      ],
      textAlignVertical: TextAlignVertical.center,
      onEditingComplete: () => {},
      controller: widget._mController,
      focusNode: widget.focusNode,
      //设置键盘类型
      keyboardType: widget.inputType,
      maxLength: widget.maxLength,
      decoration: InputDecoration(
        counterText: "",
        border: InputBorder.none,
        hintText: widget._hintText,
        hintStyle: TextStyle(
            color: Colors.grey.shade400,
            fontSize: widget.hintSize,
            fontWeight: FontWeight.w400),
        suffixIcon: _isShowUserClear!
            ? IconButton(
                icon: Icon(
                  Icons.clear,
                  color: RColors.appMain,
                ),
                onPressed: () {
                  // 清空输入框内容
                  WidgetsBinding.instance.addPostFrameCallback(
                    (_) => widget._mController.clear(),
                  );
                },
              )
            : IconButton(
                icon: Icon(null),
                onPressed: null,
              ),
      ),
    );
  }
}
