/*
 * @Author: XianKaiQun
 * @Date: 2020-08-25 14:59:08
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2021-11-02 09:51:15
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

typedef WSinglePickerFieldBuilder<T> = Widget Function(
  T value,
  Future<void> Function() trigger,
);
typedef WSinglePickerGetData<T> = Future<List<T>> Function();

typedef WSinglePickerFieldOnChanged<T> = void Function(T value);

///减少逻辑代码的单选组件
class WSinglePickerField<T extends WPickerEntity> extends StatefulWidget {
  WSinglePickerField({
    Key? key,
    required this.getData,
    required this.builder,
    this.title,
    this.value,
    this.onChanged,
  }) : super(key: key);
  final WSinglePickerFieldBuilder<T?> builder;
  final Widget? title;
  final WSinglePickerGetData<T>? getData;
  final T? value;
  final WSinglePickerFieldOnChanged<T>? onChanged;
  @override
  _WSinglePickerFieldState<T> createState() => _WSinglePickerFieldState<T>();
}

class _WSinglePickerFieldState<T extends WPickerEntity>
    extends State<WSinglePickerField<T>> {
  T? _value;

  T? get value => _value;

  @override
  void initState() {
    super.initState();
    _value = widget.value;
  }

  ///触发单选弹出层
  Future<void> _trigger() async {
    final res = await WPickerUtil.single<T>(
      context,
      title: widget.title,
      getData: widget.getData!,
      initialValue: _value,
    );
    if (res != null) {
      _onChanged(res);
    }
  }

  ///触发[widget.onChanged],
  ///刷新视图[widget.builder]
  void _onChanged(T value) {
    if (_value == value) return;
    _value = value;
    setState(() {});
    if (widget.onChanged != null) {
      widget.onChanged!(value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(value, () => _trigger());
  }
}

///picker表单
class WSinglePickerFormField<T extends WPickerEntity> extends WFormField<T?> {
  WSinglePickerFormField({
    Key? key,
    required WSinglePickerFieldBuilder<T?> builder,
    required WSinglePickerGetData<T> getData,
    required this.field,
    Widget? title,
    T? value,
    this.onChanged,
    FormFieldSetter<T>? onSaved,
    FormFieldValidator<T>? validator,
    AutovalidateMode? autovalidateMode,
    bool enabled = true,
  }) : super(
          key: key,
          field: field,
          onSaved: onSaved,
          validator: validator,
          autovalidateMode: autovalidateMode,
          enabled: enabled,
          builder: (WFormFieldState<T?> fieldState) {
            final _fieldState = fieldState as _WSinglePickerFormFieldState<T>;
            return WSinglePickerField(
              title: title,
              value: _fieldState.value,
              getData: getData,
              builder: builder,
              onChanged: (dynamic value) {
                _fieldState.didChange(value);
              },
            );
          },
        );

  ///直接使用[textField]进行builder
  WSinglePickerFormField.textField({
    Key? key,
    required WSinglePickerGetData<T> getData,
    required this.field,
    Widget? title,
    T? value,
    this.onChanged,
    TextEditingController? controller,
    FormFieldSetter<T>? onSaved,
    FormFieldValidator<T>? validator,
    AutovalidateMode? autovalidateMode,
    bool? enabled = true,
    FocusNode? focusNode,
    InputDecoration? decoration,
    TextInputType? keyboardType,
    TextCapitalization textCapitalization = TextCapitalization.none,
    TextInputAction? textInputAction,
    TextStyle? style,
    StrutStyle? strutStyle,
    TextDirection? textDirection,
    TextAlign textAlign = TextAlign.start,
    TextAlignVertical? textAlignVertical,
    bool autofocus = false,
    // bool readOnly = false,
    ToolbarOptions? toolbarOptions,
    bool? showCursor,
    String obscuringCharacter = '•',
    bool obscureText = false,
    bool autocorrect = true,
    SmartDashesType? smartDashesType,
    SmartQuotesType? smartQuotesType,
    bool enableSuggestions = true,
    MaxLengthEnforcement maxLengthEnforcement = MaxLengthEnforcement.enforced,
    int maxLines = 1,
    int? minLines,
    bool expands = false,
    int? maxLength,
    // GestureTapCallback onTap,
    VoidCallback? onEditingComplete,
    ValueChanged<String>? onFieldSubmitted,
    List<TextInputFormatter>? inputFormatters,
    double cursorWidth = 2.0,
    Radius? cursorRadius,
    Color? cursorColor,
    Brightness? keyboardAppearance,
    EdgeInsets scrollPadding = const EdgeInsets.all(20.0),
    bool enableInteractiveSelection = true,
    InputCounterWidgetBuilder? buildCounter,
    ScrollPhysics? scrollPhysics,
    Iterable<String>? autofillHints,
  }) : super(
          key: key,
          field: field,
          onSaved: onSaved,
          validator: validator,
          autovalidateMode: autovalidateMode,
          enabled: enabled ?? true,
          builder: (WFormFieldState<T?> fieldState) {
            final state = fieldState as _WSinglePickerFormFieldState<T>;
            //主题
            InputDecoration _decoration = decoration ?? InputDecoration();
            _decoration = _decoration.applyDefaults(
              Theme.of(state.context).inputDecorationTheme,
            );
            _decoration = _decoration.copyWith(
              suffixIconConstraints:
                  _decoration.suffixIconConstraints ?? const BoxConstraints(),
              suffixIcon: _decoration.suffixIcon ??
                  Icon(
                    Icons.chevron_right,
                    color: Colors.black38,
                  ),
              errorText: state.errorText,
            );
            final _controller = controller ?? TextEditingController();
            _controller.value =
                _controller.value.copyWith(text: state.value?.selectName);
            return WSinglePickerField(
              title: title,
              getData: getData,
              onChanged: (dynamic value) => state.didChange(value),
              builder: (dynamic value, trigger) {
                return TextField(
                  controller: _controller,
                  focusNode: focusNode,
                  decoration: _decoration,
                  keyboardType: keyboardType,
                  textInputAction: textInputAction,
                  style: style,
                  strutStyle: strutStyle,
                  textAlign: textAlign,
                  textAlignVertical: textAlignVertical,
                  textDirection: textDirection,
                  textCapitalization: textCapitalization,
                  autofocus: autofocus,
                  toolbarOptions: toolbarOptions,
                  readOnly: true,
                  showCursor: showCursor,
                  obscuringCharacter: obscuringCharacter,
                  obscureText: obscureText,
                  autocorrect: autocorrect,
                  smartDashesType: smartDashesType ??
                      (obscureText
                          ? SmartDashesType.disabled
                          : SmartDashesType.enabled),
                  smartQuotesType: smartQuotesType ??
                      (obscureText
                          ? SmartQuotesType.disabled
                          : SmartQuotesType.enabled),
                  enableSuggestions: enableSuggestions,
                  maxLengthEnforcement: maxLengthEnforcement,
                  maxLines: maxLines,
                  minLines: minLines,
                  expands: expands,
                  maxLength: maxLength,
                  // onChanged: onChangedHandler,
                  onTap: () => trigger(),
                  onEditingComplete: onEditingComplete,
                  onSubmitted: onFieldSubmitted,
                  inputFormatters: inputFormatters,
                  enabled: enabled ?? true,
                  cursorWidth: cursorWidth,
                  cursorRadius: cursorRadius,
                  cursorColor: cursorColor,
                  scrollPadding: scrollPadding,
                  scrollPhysics: scrollPhysics,
                  keyboardAppearance: keyboardAppearance,
                  enableInteractiveSelection: enableInteractiveSelection,
                  buildCounter: buildCounter,
                  autofillHints: autofillHints,
                );
              },
            );
          },
        );

  final String field;

  final WSinglePickerFieldOnChanged<T>? onChanged;

  @override
  _WSinglePickerFormFieldState<T> createState() =>
      _WSinglePickerFormFieldState<T>();
}

class _WSinglePickerFormFieldState<T extends WPickerEntity>
    extends WFormFieldState<T?> {
  @override
  WSinglePickerFormField<T> get widget =>
      super.widget as WSinglePickerFormField<T>;

  @override
  void didChange(T? value) {
    super.didChange(value);
    if (widget.onChanged != null) {
      widget.onChanged!(value!);
    }
  }
}
