/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-04-08 17:23:31
 * @LastEditTime : 2023-05-16 10:13:24
 * @FilePath     : /wisdom-huiguanjia-app/wisdom_cli/lib/src/form_widget/components/input_number.dart
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class WFInputNumber extends StatelessWidget {
  const WFInputNumber({
    Key? key,
    this.isRequired = false,
    this.title,
    this.type,
    this.hintText,
    this.maxLength,
    this.maxSize,
    this.onValidator,
    this.onInput,
    this.initialValue,
    this.axis,
    this.minSize,
    this.isInt = false,
  }) : super(key: key);

  ///是否必须
  final bool isRequired;

  ///标题文字
  final Widget? title;

  ///占位文字
  final String? hintText;

  ///最大长度（仅 `type==singleLine || type==multiLine` 时有效）,
  ///`singleLine` 默认64,`multiLine`,默认256
  final int? maxLength;

  final int? minSize;

  final int? maxSize;

  ///输入框类型
  final InputType? type;

  final Function(dynamic)? onInput;

  ///校验
  final String Function(String?)? onValidator;

  final initialValue;

  final Axis? axis;
  final bool isInt;
  @override
  Widget build(BuildContext context) {
    final theme = WTheme.of(context);
    final colorScheme = theme.colorScheme;
    return WisFormLayoutComponent(
      title: title,
      isRequired: isRequired,
      axis: axis ?? Axis.horizontal,
      padding:
          type == InputType.multiLine ? EdgeInsets.only(bottom: 10.pt) : null,
      child: TextFormField(
        onChanged: (v) => onInput!(v),
        validator: (v) => onValidator!(v),
        initialValue: initialValue != null && initialValue is num
            ? initialValue.toString()
            : initialValue,
        keyboardType: () {
          return TextInputType.numberWithOptions(decimal: true);
        }(),
        inputFormatters: [
          _MoneyTextInputFormatter(),
        ],
        style: TextStyle(
          fontSize: 14.pt,
          color:
              type == InputType.money ? colorScheme.danger : colorScheme.minor,
        ),
        minLines: type == InputType.multiLine ? 3 : 1,
        maxLines: type == InputType.multiLine ? 3 : 1,
        maxLength: type == InputType.multiLine ? (maxLength ?? 256) : null,
        decoration: InputDecoration(
          contentPadding: type == InputType.multiLine
              ? EdgeInsets.fromLTRB(15.pt, 0, 0, 0)
              : null,
          fillColor: Colors.transparent,
          filled: true,
          hintText: hintText,
          hintStyle: TextStyle(
            fontSize: 14.pt,
            color: colorScheme.placeholder,
            fontWeight: FontWeight.w300,
          ),
        ),
      ),
    );
  }
}

// class _NumberInputFormatter extends TextInputFormatter {
//   final regExp = RegExp('^[1-9]+[0-9]+\$');
//   @override
//   TextEditingValue formatEditUpdate(oldValue, newValue) {
//     if ((newValue?.text?.length ?? 0) == 0) return TextEditingValue();
//     return regExp.hasMatch(newValue?.text ?? '') ? newValue : oldValue;
//   }
// }

class _MoneyTextInputFormatter extends TextInputFormatter {
  final regExp = RegExp('^[0-9]+\.?([0-9]{1,2})?\$');
  @override
  TextEditingValue formatEditUpdate(oldValue, newValue) {
    if (newValue.text == '')
      return TextEditingValue();

    ///打上0自动加上小数点
    else if (newValue.text == '0') {
      if (oldValue.text.length > newValue.text.length) {
        return TextEditingValue();
      } else {
        return TextEditingValue(
          text: '0.',
          selection: TextSelection(baseOffset: 2, extentOffset: 2),
        );
      }
    } else {
      return regExp.hasMatch(newValue.text) ? newValue : oldValue;
    }
  }
}

class NumberTextInputFormatter extends TextInputFormatter {
  NumberTextInputFormatter({this.decimalRange})
      : assert(decimalRange == null || decimalRange > 0);

  final int? decimalRange;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    TextEditingValue _newValue = this.sanitize(newValue);
    String text = _newValue.text;

    if (decimalRange == null) {
      return _newValue;
    }

    if (text == '.') {
      return TextEditingValue(
        text: '0.',
        selection: _newValue.selection.copyWith(baseOffset: 2, extentOffset: 2),
        composing: TextRange.empty,
      );
    }

    return this.isValid(text) ? _newValue : oldValue;
  }

  bool isValid(String text) {
    int dots = '.'.allMatches(text).length;

    if (dots == 0) {
      return true;
    }

    if (dots > 1) {
      return false;
    }

    return text.substring(text.indexOf('.') + 1).length <= decimalRange!;
  }

  TextEditingValue sanitize(TextEditingValue value) {
    if (false == value.text.contains('-')) {
      return value;
    }

    String text = '-' + value.text.replaceAll('-', '');

    return TextEditingValue(
        text: text, selection: value.selection, composing: TextRange.empty);
  }
}
