/*
 * @Author: XianKaiQun
 * @Date: 2020-08-06 15:20:51
 * @LastEditors: XianKaiQun
 * @LastEditTime: 2020-08-25 17:19:27
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class WisPicker<T> extends StatefulWidget {
  WisPicker({
    Key? key,
    required this.getData,
    required this.name,
    required this.unique,
    this.multiple = false,
    this.dense = true,
    this.selects = const [],
    this.onChanged,
  })  : assert(selects.length <= 1 || multiple == true),
        super(key: key);
  final bool multiple;
  final bool dense;
  final Future<List<T>> getData;
  final List<T?> selects;
  final String Function(T) name;
  final dynamic Function(T) unique;
  final void Function(List<T>? selects, bool isTap)? onChanged;
  @override
  _WisPickerState<T> createState() => _WisPickerState<T>();
}

class _WisPickerState<T> extends State<WisPicker<T?>> {
  late dynamic Function(T?) uniquefn;

  bool loading = false;

  List<T?> list = [];

  List<T?>? selects;

  @override
  void initState() {
    super.initState();
    uniquefn = widget.unique;
    selects = widget.selects;
    widget.onChanged!(selects, false);
    getData();
  }

  void getData() async {
    loading = true;
    try {
      list = await widget.getData;
    } finally {
      loading = false;
    }
    setState(() {});
  }

  ///点击事件
  ///会触发widget.onChanged(selects, true);

  void ontap(T? value) {
    if (!widget.multiple) {
      selects = [value];
    } else {
      final exit = selected(value);
      if (exit) {
        selects!.removeWhere((e) => uniquefn(e) == uniquefn(value));
      } else {
        selects!.add(value);
      }
    }
    setState(() {});
    widget.onChanged!(selects, true);
  }

  ///是否已经选中？
  ///判断唯一值
  bool selected(value) {
    return selects!.indexWhere((e) => uniquefn(e) == uniquefn(value)) != -1;
  }

  @override
  Widget build(BuildContext context) {
    if (loading) return Center(child: WLoading());

    return ListView(
      children: ListTile.divideTiles(
        context: context,
        tiles: list
            .map(
              (value) => ListTile(
                onTap: () => ontap(value),
                dense: widget.dense,
                selected: selected(value),
                title: Text(widget.name(value),),
              ),
            )
            .toList(),
      ).toList(),
    );
  }
}
