import 'package:account_center/widget/form/form_edit_clear.dart';
import 'package:account_center/widget/form/form_row.dart';
import 'package:flutter/material.dart';

/// 表单输入框样式
class FormInput extends StatelessWidget {
  final String title;
  final TextEditingController controller;
  final String hint;
  final ValueChanged? changed;
  final FocusNode focusNode;
  final int maxLength; //最大输入长度
  final String? regExp; //正则表达式规则
  final TextInputType inputType; //输入类型
  /// 是否显示必填*
  final bool isRequired;
  final bool enabled;
  final bool check;
  final Widget? endWidget;

  /// 额外显示的错误
  final bool? Function()? showErr;
  final String? Function()? getErrText;

  const FormInput(
      {Key? key,
      required this.title,
      required this.controller,
      this.hint = '',
      this.changed,
      required this.focusNode,
      this.maxLength = 11,
      this.regExp,
      this.isRequired = false,
      this.inputType = TextInputType.text,
      this.enabled = true,
      this.check = false,
      this.showErr,
      this.getErrText,
      this.endWidget})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FormRow(
      title: title,
      isRequired: isRequired,
      enabled: enabled,
      crossAxisAlignment: CrossAxisAlignment.start,
      child: endWidget != null
          ? Row(
              children: [
                Expanded(child: _buildInput()),
                endWidget!,
              ],
            )
          : _buildInput(),
    );
  }

  FormEditClear _buildInput() {
    return FormEditClear(
      maxLength: maxLength,
      controller: controller,
      focusNode: focusNode,
      hint: hint.isEmpty ? '请输入$title' : hint,
      regExp: regExp,
      inputType: inputType,
      changed: changed,
      enabled: enabled,
      getErrText: () {
        if (check) {
          return getErrText?.call() ??
              (emptyInput() || forceShowErr() ? '请输入正确的$title' : null);
        } else {
          return null;
        }
      },
    );
  }

  /// 强制显示错误
  bool forceShowErr() => showErr?.call() == true;

  bool emptyInput() {
    return (isRequired && controller.text.isEmpty);
  }
}
