/*
 * @Author: XianKaiQun
 * @LastEditors  : WuWei
 * @Date: 2020-10-27 17:37:27
 * @LastEditTime : 2023-05-25 15:49:46
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

///单项选择
class WFSinglePicker extends StatelessWidget {
  const WFSinglePicker({
    Key? key,
    this.isRequired = false,
    this.hintText,
    this.title,
    this.initialValue,
    this.enableValue,
    this.onChanged,
    this.dataList,
    this.label,
    this.value,
    this.isSearch,
    this.axis,
    this.titleWidth,
    this.model,
  }) : 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 bool? isSearch;

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

  /// 确认选择
  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 _hintText = hintText ?? '请选择';

    _findValue() {
      if (dataList == null || dataList!.length == 0) return null;
      List<String> labelArr = [];
      for (int i = 0; i < dataList!.length; i++) {
        labelArr.add(dataList![i][_label]);
      }
      int index = dataList!.indexWhere((data) => data[_value] == _initialValue);
      return index >= 0 ? labelArr[index] : null;
      // return null;
    }

    _selectValue() {
      return _initialValue != null
          ? SinglePickerEntity(
              name: _findValue() ?? null, unique: _initialValue)
          : 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
                  ? TextFormField(
                      controller: TextEditingController(
                        text: _initialValue == '' || _initialValue == null
                            ? _hintText
                            : _findValue(),
                      ),
                      readOnly: true,
                      onTap: () async {
                        final res =
                            await WPickerUtil.single<SinglePickerEntity>(
                          context,
                          title: title,
                          initialValue: _selectValue(),
                          getData: () => SinglePickerEntity.listMap2entity(
                              dataList!, _label, _value,
                              enableValue: enableValue),
                          isSearch: isSearch,
                        );
                        if (res != null) {
                          _initialValue = res.unique;
                          setState(() {});
                          if (onChanged != null) onChanged!(res.unique);
                        }
                      },
                      style: TextStyle(
                        fontSize: 14.pt,
                        color: colorScheme.minor,
                      ),
                      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.single<SinglePickerEntity>(
                          context,
                          title: title,
                          getData: () => SinglePickerEntity.listMap2entity(
                            dataList!,
                            _label,
                            _value,
                            enableValue: enableValue,
                          ),
                          isSearch: isSearch,
                        );
                        if (res != null) {
                          _initialValue = res.unique;
                          setState(() {});
                          if (onChanged != null) onChanged!(res.unique);
                        }
                      },
                      child: WisText(
                        _hintText,
                        color: colorScheme.placeholder2,
                        size: 15.pt,
                      ),
                    ).asExpanded(),
              _initialValue != null
                  ? WFClose(
                      onTap: () {
                        _initialValue = null;
                        setState(() {});
                        if (onChanged != null) onChanged!(null);
                      },
                    )
                  : Icon(
                      FaIcons.angle_right,
                      size: 18.pt,
                      color: colorScheme.placeholder,
                    )
            ],
          );
        },
      ),
    );
  }
}
