/*
 * @Author: XianKaiQun
 * @LastEditors: wjc
 * @Date: 2020-10-26 11:07:14
 * @LastEditTime: 2022-12-07 17:27:07
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

///输入框
class WFInput extends StatefulWidget {
  const WFInput({
    Key? key,
    this.isRequired = false,
    this.isShowRequired = true,
    this.title,
    this.type = InputType.singleLine,
    this.hintText,
    this.hintStyle,
    this.maxLength,
    this.onValidator,
    this.onInput,
    this.initialValue,
    this.minLines,
    this.maxLines,
    this.border,
    this.padding,
    this.borderRadius,
    this.enable = true,
  }) : super(key: key);

  ///是否必须
  final bool isRequired;

  ///是否显示必填星号
  final bool isShowRequired;

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

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

  /// hint 样式
  final TextStyle? hintStyle;

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

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

  final Function(dynamic)? onInput;

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

  final int? minLines;
  final int? maxLines;

  final initialValue;

  /// 是否增加边框
  final Border? border;

  /// 外边距
  final padding;

  final borderRadius;
  final bool enable;

  @override
  _WFInputState createState() => _WFInputState();
}

class _WFInputState extends State<WFInput> {
  // final TextEditingController _textFieldController = TextEditingController();
  @override
  void initState() {
    // _textFieldController.text = widget.initialValue;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final _border = widget.border;
    final _padding = widget.padding;
    final _borderRadius = widget.borderRadius;
    final _enable = widget.enable;
    final colorScheme = WTheme.of(context).colorScheme;
    final _initialValue = widget.initialValue;
    return WisFormLayoutComponent(
      title: widget.title,
      isRequired: widget.isRequired,
      isShowRequired: widget.isShowRequired,
      axis:
          widget.type == InputType.multiLine ? Axis.vertical : Axis.horizontal,
      padding: widget.type == InputType.multiLine
          ? EdgeInsets.only(bottom: 10.pt)
          : null,
      child: Wisdom(
        border: _border ??
            Border.all(
              color: Colors.transparent,
            ),
        color: _enable ? Colors.transparent : colorScheme.divider,
        padding: _padding ?? null,
        borderRadius: _borderRadius ?? null,
        child: TextFormField(
          enabled: _enable,
          onChanged: (v) => widget.onInput!(v),
          validator: (v) => widget.onValidator!(v),
          initialValue: _initialValue != null
              ? (_initialValue is String
                  ? _initialValue
                  : _initialValue.toString())
              : '',
          keyboardType: () {
            switch (widget.type) {
              case InputType.money:
                return TextInputType.numberWithOptions(decimal: true);
              case InputType.phoneNumber:
                return TextInputType.phone;
              case InputType.number:
                return TextInputType.numberWithOptions(decimal: false);
              case InputType.tel:
                return TextInputType.phone;
              default:
                return TextInputType.text;
            }
          }(),
          inputFormatters: [
            if (widget.type == InputType.singleLine)
              _SingleLineInputFormatter(maxLength: widget.maxLength),
            if (widget.type == InputType.phoneNumber)
              _PhoneNumberInputFormatter(),
            if (widget.type == InputType.tel) _TelInputFormatter(),
            // if (type == InputType.money) _MoneyTextInputFormatter(),
            // if (type == InputType.number) _NumberInputFormatter(),
          ],
          style: TextStyle(
            fontSize: 14.pt,
            color: widget.type == InputType.money
                ? colorScheme.danger
                : colorScheme.minor,
          ),
          minLines: widget.type == InputType.multiLine
              ? widget.minLines ?? 3
              : widget.minLines ?? 1,
          maxLines: widget.type == InputType.multiLine
              ? widget.minLines ?? 3
              : widget.minLines ?? 1,
          maxLength: widget.type == InputType.multiLine
              ? (widget.maxLength ?? 256)
              : null,
          decoration: InputDecoration(
            contentPadding: widget.type == InputType.multiLine
                ? EdgeInsets.fromLTRB(15.pt, 0, 0, 0)
                : null,
            fillColor: _enable ? Colors.transparent : colorScheme.divider,
            filled: true,
            hintText: widget.hintText,
            hintStyle: widget.hintStyle ??
                TextStyle(
                  fontSize: 15.pt,
                  color: colorScheme.placeholder2,
                ),
          ),
        ),
      ),
    );
  }
}

///单行输入（限制输入`maxLength`字）
class _SingleLineInputFormatter extends TextInputFormatter {
  _SingleLineInputFormatter({this.maxLength});
  final int? maxLength;

  @override
  TextEditingValue formatEditUpdate(_, newValue) {
    final _maxLength = maxLength ?? 64;
    TextEditingValue value = newValue;
    final length = value.text.length;
    if (length > _maxLength)
      value = value.copyWith(
        text: value.text.substring(0, _maxLength),
      );
    return value;
  }
}

enum InputType {
  ///单行
  singleLine,

  ///多行
  multiLine,

  ///手机号
  phoneNumber,

  ///金额
  money,

  ///数字
  number,

  /// 密码

  /// 固话
  tel,
}

///手机号（限制输入数字）
class _PhoneNumberInputFormatter extends TextInputFormatter {
  final regExp = RegExp(
      '^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}');
  final int _maxLength = 11;
  @override
  TextEditingValue formatEditUpdate(oldValue, newValue) {
    TextEditingValue value = newValue;
    final length = value.text.length;
    if (length == 0) return TextEditingValue();
    if (length > _maxLength)
      value = value.copyWith(
        text: value.text.substring(0, _maxLength),
      );
    // return regExp.hasMatch(newValue?.text ?? '') ? newValue : oldValue;
    return value;
  }
}

class _TelInputFormatter extends TextInputFormatter {
  final regExp = RegExp(
      '^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}');
  final int _maxLength = 12;
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    TextEditingValue value = newValue;
    final length = value.text.length;
    if (length == 0) return TextEditingValue();
    if (length > _maxLength)
      value = value.copyWith(
        text: value.text.substring(0, _maxLength),
      );
    // return regExp.hasMatch(newValue?.text ?? '') ? newValue : oldValue;
    return value;
  }
}
