// ignore_for_file: unnecessary_set_literal

/*
 * @Author       : WuWei
 * @LastEditors: ChenYaJin
 * @Date         : 2022-02-21 09:55:25
 * @LastEditTime: 2023-04-06 09:39:54
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

///两层选择
class WFTreePicker extends StatelessWidget {
  const WFTreePicker({
    Key? key,
    this.isRequired = false,
    this.hintText,
    this.title,
    required this.initialValue,
    this.enableValue,
    required this.onChanged,
    required this.dataList,
    required this.label,
    required this.value,
    this.isSearch,
    this.axis,
    this.titleWidth,
    this.model,
    this.isMulti,
    required this.child,
    required this.firstName,
    required this.firstValue,
  }) : super(key: key);

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

  final model;

  ///是否必须
  final bool? isRequired;

  /// 提示语，placeholder
  final String? hintText;

  /// 表格标题
  final Widget? title;

  /// 单选初始值
  final initialValue;

  final List? enableValue;

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

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

  /// 第二级
  final String? child;
  final String? firstName;
  final String? firstValue;

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

  /// 选择数据列表 (json对象格式，非map)
  final List? dataList;

  /// 是否多选
  final bool? isMulti;

  /// 确认选择
  final void Function(dynamic value) onChanged;

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    var _initialValue = initialValue;
    var _label = label ?? 'label';
    var _value = value ?? 'value';
    var _child = child ?? 'child';
    var _firstName = firstName ?? 'firstName';
    var _firstValue = firstValue ?? 'firstValue';
    var _hintText = hintText ?? '请选择';

    _findValue() {
      if (isMulti == true) {
        List arr = [];
        dataList!.forEach((element) {
              element[_child].forEach((item) => {
                    if (_initialValue.contains(item[_value]))
                      {
                        arr.add(item[_label]),
                      }
                  });
            });
        return arr.length > 0 ? arr.join('\r、') : null;
      } else {
        if (dataList!.length == 0) return null;
        List arr = [];
        dataList!.forEach((element) => {
              element[_child].forEach((item) => {
                    if (_initialValue == item[_value])
                      {
                        arr.add(item[_label]),
                      }
                  })
            });
        return arr.length > 0 ? arr[0] : null;
      }
    }

    List _selectValue = [];
    _getSelectValue() {
      if (_initialValue == null ||
          (isMulti == true && _initialValue.length == 0)) return null;
      if (isMulti == true) {
        _initialValue.forEach((item) => {
              _selectValue.add({_value: item}),
            });
      } else {
        _selectValue = [
          {_value: _initialValue}
        ];
      }
      return _selectValue;
    }

    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
                  ? TextFormField(
                      controller: TextEditingController(
                        text: _initialValue == null || _initialValue.length == 0
                            ? null
                            : _findValue(),
                      ),
                      readOnly: true,
                      onTap: () async {
                        final res = await WPickerUtil.tree<SinglePickerEntity>(
                          context,
                          title: title,
                          initialValue: _getSelectValue(),
                          label: _label,
                          value: _value,
                          child: _child,
                          firstName: _firstName,
                          firstValue: _firstValue,
                          data: dataList!,
                          isSearch: isSearch,
                          isMulti: isMulti,
                        );
                        if (res != null) {
                          if (isMulti == true) {
                            setState(() {});
                            onChanged(res == []
                                ? null
                                : res.map((e) => e.unique).toList());
                          } else {
                            _initialValue = res != [] ? res[0].name : res;
                            setState(() {});
                            onChanged(res != [] ? res[0].unique : res);
                          }
                        }
                      },
                      style: TextStyle(
                        fontSize: 14.pt,
                        color: colorScheme.mainTitle,
                      ),
                      decoration: InputDecoration(
                        // contentPadding: EdgeInsets.symmetric(
                        //   vertical: 3.pt,
                        //   horizontal: 6.pt,
                        // ),
                        fillColor: Colors.transparent,
                        filled: true,
                        hintText: _hintText,
                        hintStyle: TextStyle(
                          fontSize: 15.pt,
                          // color: colorScheme.placeholder,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ).asExpanded()
                  : Wisdom.row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      onTap: () async {
                        final res = await WPickerUtil.tree<SinglePickerEntity>(
                          context,
                          title: title,
                          label: _label,
                          value: _value,
                          child: _child,
                          firstName: _firstName,
                          firstValue: _firstValue,
                          initialValue: _getSelectValue(),
                          data: dataList!,
                          isSearch: isSearch,
                          isMulti: isMulti,
                        );
                        if (res != null) {
                          if (res.length > 0 && isMulti == true) {
                            setState(() {});
                            onChanged(res.map((e) => e.unique).toList());
                          } else {
                            _initialValue = res[0].name;
                            setState(() {});
                             onChanged(res[0].unique);
                          }
                        }
                      },
                      children: [
                        WisText(
                          _hintText,
                          color: colorScheme.placeholder,
                          size: 15.pt,
                          overflow: TextOverflow.ellipsis,
                        ).asExpanded(),
                      ],
                    ).asExpanded(),
              _initialValue != null && _initialValue.length != 0
                  ? WFClose(
                      onTap: () {
                        _initialValue = null;
                        setState(() {});
                        onChanged(null);
                      },
                    )
                  : Icon(
                      FaIcons.angle_right,
                      size: 18.pt,
                      color: colorScheme.placeholder,
                    )
            ],
          );
        },
      ),
    );
  }
}
