/*
 * @Author: XianKaiQun
 * @LastEditors  : WuWei
 * @Date: 2020-10-26 11:07:42
 * @LastEditTime : 2023-05-25 15:50:07
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class WFMultiplePicker extends StatelessWidget {
  const WFMultiplePicker({
    Key? key,
    this.isRequired,
    this.hintText,
    this.title,
    required this.onChanged,
    this.initialValue,
    this.enableValue,
    this.dataList,
    this.label,
    this.value,
    this.axis,
    this.isSearch,
    this.titleWidth,
  }) : super(key: key);

  /// 是否可搜索
  final bool? isSearch;

  ///布局
  final Axis? axis;
  final titleWidth;

  ///是否必须
  final bool? isRequired;
  final String? hintText;
  final Widget? title;
  final List? initialValue;
  final List? enableValue;
  final void Function(List? values) onChanged;

  /// 多选项对应的名称 { 'name': '标题名称', id: '999999'} 这里的[name]就是对应[label] 默认是'label'
  final String? label;

  /// 多选项对应的值 { 'name': '标题名称', id: '999999'} 这里的[id]就是对应[value] 默认是'value'
  final String? value;

  /// 选择数据列表
  final dataList;

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;

    List? _initialValue = initialValue ?? [];
    var _label = label ?? 'label';
    var _value = value ?? 'value';
    List<SinglePickerEntity> _selectValue = [];

    _getSelectValue() {
      if (_initialValue == null || _initialValue!.length == 0) return null;
      List tempList;
      _initialValue!.forEach((item) {
            tempList = dataList.where((v) => v[_value] == item).toList();
            _selectValue.add(SinglePickerEntity(
              name: tempList[0][_label],
              unique: tempList[0][_value],
            ));
          });
      return _selectValue;
    }

    _findValue() {
      List arr = dataList
          .map((data) =>
              _initialValue!.contains(data[_value]) ? data[_label] : null)
          .where((dataLabel) => dataLabel != null)
          .toList();
      return arr.length > 0 ? arr.join('\r、') : null;
    }

    return WisFormLayoutComponent(
      title: title,
      titleWidth: titleWidth,
      isRequired: isRequired,
      axis: axis ?? Axis.horizontal,
      child: StatefulBuilder(
        builder: (BuildContext context, setState) {
          return Wisdom.row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            padding: EdgeInsets.only(left: 10.pt),
            children: [
              _initialValue != null && _initialValue!.length > 0
                  ? TextField(
                      controller: TextEditingController(
                        text: (_initialValue!.length > 0) ? _findValue() : ' ',
                      ),
                      readOnly: true,
                      onTap: () async {
                        final res =
                            await WPickerUtil.multiple<SinglePickerEntity>(
                          context,
                          title: title,
                          initialValue: _getSelectValue(),
                          getData: () => SinglePickerEntity.listMap2entity(
                            dataList,
                            _label,
                            _value,
                            enableValue: enableValue,
                          ),
                          isSearch: isSearch,
                        );
                        if (res != null) {
                          onChanged(res.map((e) => e.unique).toList());
                        }
                      },
                      style: TextStyle(
                        fontSize: 14.pt,
                        color: colorScheme.minor,
                      ),
                      minLines: 1,
                      maxLines: 999,
                      decoration: InputDecoration(
                        fillColor: Colors.transparent,
                        filled: true,
                        hintText: hintText,
                        hintStyle: TextStyle(
                          fontSize: 14.pt,
                          color: colorScheme.placeholder,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ).asExpanded()
                  : Wisdom(
                      onTap: () async {
                        final res =
                            await WPickerUtil.multiple<SinglePickerEntity>(
                          context,
                          title: title,
                          getData: () => SinglePickerEntity.listMap2entity(
                              dataList, _label, _value,
                              enableValue: enableValue),
                          isSearch: isSearch,
                        );
                        if (res != null) {
                          onChanged(res.map((e) => e.unique).toList());
                        }
                      },
                      child: WisText(
                        hintText ?? '请选择',
                        color: colorScheme.placeholder,
                        weight: FontWeight.w300,
                        size: 14.pt,
                      ),
                    ).asExpanded(),
              _initialValue != null && _initialValue!.length != 0
                  ? WFClose(
                      onTap: () {
                        _initialValue = null;
                        setState(() {});
                        onChanged(null);
                      },
                    )
                  : Icon(
                      FaIcons.angle_right,
                      size: 18.pt,
                      color: colorScheme.placeholder,
                    )
            ],
          );
        },
      ),
    );
  }
}
