/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-08-04 09:14:43
 * @LastEditTime : 2021-11-30 16:30:23
 * @Description  : Do not edit
 */

part of '../index.dart';

// ignore: must_be_immutable
class DropdownFilter extends StatefulWidget {
  DropdownFilter({
    Key? key,
    this.filters,
    this.color,
    this.height,
    this.textStyle,
  }) : super(key: key);

  @required
  List<FilterButton>? filters;
  final Color? color;
  final double? height;
  final TextStyle? textStyle;

  @override
  _DropdownFilterState createState() => _DropdownFilterState();
}

class _DropdownFilterState extends State<DropdownFilter>
    with SingleTickerProviderStateMixin {
  bool isMask = false; //下拉蒙层是否显示
  FilterButton? current;
  int? currentIndex;
  late Animation<double> animation;
  late AnimationController controller;
  GlobalKey<_DropdownFilterState> _globalKey =
      new GlobalKey<_DropdownFilterState>();
  OverlayEntry? overlayEntry;
  IndexStore get store => Provider.of(context, listen: false);

  @override
  void initState() {
    super.initState();
    controller = new AnimationController(
        duration: Duration(milliseconds: 200), vsync: this);
    animation = new Tween(begin: 0.0, end: 294.pt).animate(controller)
      ..addListener(() {
        //这行如果不写，没有动画效果
        setState(() {});
      });
  }

  void _getWidgetHeight() {
    // print(_globalKey.currentContext.size.height);
  }

  void onChangeFilterItem(item, index) {
    _getWidgetHeight();

    /// 有回调事件 无遮罩
    if (item.callback != null) {
      controller.reverse();
      item.callback();
    } else {
      if (animation.status == AnimationStatus.completed) {
        controller.reverse();
      } else {
        controller.forward();
      }
    }

    /// 设置当前筛选的项
    /// 是否等于当前项 是则置灰
    if (currentIndex != index) {
      setState(() {
        current = item;
        currentIndex = index;
      });
    } else {
      setState(() {
        current = null;
        currentIndex = null;
      });
    }

    /// 是否下拉遮罩
    if (item.isDrop) {
      triggerMask();
    } else {
      setState(() {
        store.onSetShowButtonMask(false);
        isMask = false;
      });
    }
  }

  void triggerMask() {
    setState(() {
      isMask = !isMask;
      store.onSetShowButtonMask(isMask);
    });
  }

  /// 选择筛选项
  void onCheckItem(item) {
    setState(() {
      item['check'] = item['check'] == null || !item['check'] ? true : false;
    });
  }

  void onReset() {
    if (current != null &&
        current!.contents != null &&
        current!.contents!.length > 0) {
      setState(() {
        current!.contents!.forEach((element) {
          element['check'] = false;
        });
      });
    }
  }

  Future onSubmit() async {
    List tempArr = [];
    current!.contents!.forEach((element) {
      if (element['check'] != null && element['check'] == true) {
        tempArr.add(element);
      }
    });
    store.onChooseListItem(tempArr);
    onChangeFilterItem(current, currentIndex);
  }

  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    return Stack(
      key: _globalKey,
      clipBehavior: Clip.hardEdge,
      children: <Widget>[
        /// 筛选栏
        Wisdom.row(
          border: Border(
            bottom: BorderSide(
                color: isMask ? colorScheme.divider : Colors.transparent,
                width: 0.5),
          ),
          color: widget.color ?? Colors.white,
          height: widget.height ?? 44.pt,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: List.generate(widget.filters!.length, (index) {
            var item = widget.filters![index];
            return _BuildFilterButton(
              item: item,
              textStyle: widget.textStyle,
              onChange: () => {
                onChangeFilterItem(item, index),
              },
              status: currentIndex == null
                  ? 'up'
                  : currentIndex == index
                      ? 'down'
                      : 'up',
            );
          }),
        ),
        Positioned(
          top: widget.height ?? 44.pt,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              Container(
                  width: MediaQuery.of(context).size.width,
                  color: Colors.white,
                  height: animation.value,
                  child: Stack(
                    children: [
                      ListView(
                        scrollDirection: Axis.vertical,
                        // itemExtent: 50.pt,
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.pt,
                        ),
                        children: <Widget>[
                          if (current != null &&
                              current!.contents != null &&
                              current!.contents!.length > 0) ...[
                            for (var item in current?.contents ?? [])
                              Wisdom(
                                onTap: () => {onCheckItem(item)},
                                width:
                                    (MediaQuery.of(context).size.width - 40) /
                                        2,
                                child: Container(
                                  margin: EdgeInsets.only(left: 5, right: 5),
                                  alignment: Alignment.centerLeft,
                                  width: MediaQuery.of(context).size.width,
                                  height: 40,
                                  child: Row(
                                    children: [
                                      if (item['check'] != null &&
                                          item['check'] == true) ...[
                                        Image(
                                          image: AssetList.$xzh_png_image,
                                          height: 10.pt,
                                        ),
                                        SizedBox(width: 5.pt),
                                      ],
                                      WisText(
                                        '${item['name']}',
                                        color: (item['check'] != null &&
                                                item['check'] == true)
                                            ? colorScheme.primary
                                            : colorScheme.minor,
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                          ],
                          SizedBox(
                            height: 79.pt,
                          )
                        ],
                      ),
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Wisdom(
                          color: Colors.white,
                          padding: EdgeInsets.all(15.pt),
                          child: Wisdom.row(
                            height: 34.pt,
                            border: Border.all(
                                width: 1.pt, color: colorScheme.primary),
                            borderRadius: BorderRadius.circular(4.pt),
                            children: [
                              Wisdom(
                                onTap: () => onReset(),
                                alignment: Alignment.center,
                                height: 34.pt,
                                child: WisText(
                                  '重置',
                                  color: colorScheme.primary,
                                  size: 14.pt,
                                ),
                              ).asExpanded(),
                              Wisdom(
                                onTap: () => onSubmit(),
                                alignment: Alignment.center,
                                borderRadius: BorderRadius.only(
                                  topRight: Radius.circular(4.pt),
                                  bottomRight: Radius.circular(4.pt),
                                ),
                                color: colorScheme.primary,
                                height: 34.pt,
                                child: WisText(
                                  '确认',
                                  color: Colors.white,
                                  size: 14.pt,
                                ),
                              ).asExpanded(),
                            ],
                          ),
                        ),
                      )
                    ],
                  )),

              /// 筛选内容
              if (isMask) ...[
                Container(
                  height: 5000.pt,
                  decoration: BoxDecoration(
                    color: Colors.black54,
                  ),
                )
              ]
            ],
          ),
        ),
      ],
    );
  }
}

/// 筛选项
class _BuildFilterButton extends StatelessWidget {
  const _BuildFilterButton({
    Key? key,
    this.item,
    this.textStyle,
    this.status,
    this.onChange,
  }) : super(key: key);

  final item;
  final TextStyle? textStyle;
  final Function? onChange;
  final status;

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    String? name = '';
    if (item?.checkList != null && item.checkList.length > 0) {
      name = item.checkList.map((check) => check['name']).toList().join('、');
    }
    return Wisdom.row(
        width: (MediaQuery.of(context).size.width - 40) / 2,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        height: 44.pt,
        onTap: () => {
              onChange!(),
            },
        children: [
          /// 状态栏 文字超出问题 蠢方法解决了
          if ((item?.checkList != null && item.checkList.length > 0)) ...[
            WisText(
              '$name',
              color: (status == 'down' ||
                      (item?.checkList != null && item.checkList.length > 0))
                  ? colorScheme.primary
                  : colorScheme.mainTitle,
              size: textStyle?.fontSize ?? 15.pt,
              weight: textStyle?.fontWeight ?? FontWeight.w300,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              textAlign: TextAlign.center,
            ).asExpanded(),
          ] else ...[
            WisText(
              '${item.title}',
              color: (status == 'down' ||
                      (item?.checkList != null && item.checkList.length > 0))
                  ? colorScheme.primary
                  : colorScheme.mainTitle,
              size: textStyle?.fontSize ?? 15.pt,
              weight: textStyle?.fontWeight ?? FontWeight.w300,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              textAlign: TextAlign.center,
            ),
          ],
          if (item.hasIcon) ...[
            SizedBox(width: 5.pt),
            status == 'down' ? item.dropdownIcon : item.icon,
          ]
        ]).asExpanded();
  }
}

class FilterButton {
  String? title; //按钮title
  List? contents; //下拉列表
  String? type; //下拉筛选类型 'Column'、'Row'
  Function? callback; //按钮点击回调，可以自定义回调，如跳转页面等
  String? direction; //下拉箭头方向
  Color? color; // 背景颜色
  Image? icon; //正常显示图标
  Image? dropdownIcon; // 下拉图标
  bool? hasIcon;
  bool? isDrop;
  List? checkList;

  FilterButton({
    this.title,
    this.contents,
    this.type,
    this.callback,
    this.direction,
    this.color,
    this.hasIcon,
    this.dropdownIcon,
    this.icon,
    this.isDrop,
    this.checkList,
  });
}
