/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-08-04 09:14:43
 * @LastEditTime : 2023-06-13 17:04:03
 * @Description  : Do not edit
 */

import 'package:flutter/material.dart';
import 'package:task_package/src/assets.gen.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

import '../models/task_inventory_tree_model.dart';

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

  @required
  List? filters;
  final Color? color;
  final double? height;
  final TextStyle? textStyle;
  final store;
  List? checkList;
  List<TaskInventoryTreeModel>? contents; //下拉列表
  final Function(dynamic data, int? currentIndex)? onChooseListItem;

  @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;

  /// 任务类型
  String inventoryFirstId = '';
  String? inventorySecondId;
  List inventoryIds = [];
  List inventoryItems = [];
  var inventoryItem = TaskInventoryTreeModel();

  var taskItemListTree = [];
  var taskItemSecondList = [];
  // 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 != null && 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 != null && item.isDrop) {
      triggerMask();
    } else {
      setState(() {
        isMask = false;
      });
    }
  }

  void triggerMask() {
    setState(() {
      isMask = !isMask;
    });
  }

  void onReset() {
    if (widget.contents != null && widget.contents!.length > 0) {
      setState(() {});
      changeFirstInventoryValue('');
      changeSecondInventoryValue('');
      setInventorySecondList([]);
    }
    widget.onChooseListItem!([], null);
    onChangeFilterItem(null, null);
  }

  Future onSubmit() async {
    widget.onChooseListItem!(inventoryItems, currentIndex);
    onChangeFilterItem(current, currentIndex);
  }

  changeFirstInventoryValue(id) {
    setState(() {
      inventoryFirstId = id;
    });
  }

  changeSecondInventoryValue(item) {
    setState(() {
      if (item == '' || item == null) {
        inventoryIds = [];
        inventoryItems = [];
        return;
      }
      if (inventoryIds.contains(item.id)) {
        inventoryIds.remove(item.id);
        inventoryItems.remove(item);
      } else {
        inventoryIds.add(item.id);
        inventoryItems.add(item);
      }
    });
  }

  setInventorySecondList(list) {
    setState(() {
      taskItemSecondList = list;
      if (list.length == 0) {
        inventoryIds = [];
      }
    });
  }

  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),
              },
              contents: widget.contents,
              checkList: widget.checkList,
              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 (widget.contents != null &&
                              widget.contents!.length > 0) ...[
                            Wisdom.row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(4.pt),
                              height: 240.pt,
                              children: [
                                SingleChildScrollView(
                                  key: Key('taskHallFilterInner1'),
                                  child: Wisdom.column(
                                    width: (MediaQuery.of(context).size.width -
                                            100.pt) /
                                        2,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Wisdom.row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        padding:
                                            EdgeInsets.fromLTRB(15.pt, 0, 0, 0),
                                        height: 38.pt,
                                        onTap: () => {
                                          changeFirstInventoryValue(''),
                                          setInventorySecondList([]),
                                        },
                                        color: inventoryFirstId == ''
                                            ? Color.fromRGBO(246, 247, 252, 1)
                                            : Colors.white,
                                        children: [
                                          if (inventoryFirstId == '') ...[
                                            Container(
                                              height: 15.pt,
                                              width: 3.pt,
                                              color: colorScheme.primary,
                                              margin:
                                                  EdgeInsets.only(right: 10.pt),
                                            ),
                                          ],
                                          WisText(
                                            '全部',
                                            size: 13.pt,
                                            color: inventoryFirstId == ''
                                                ? colorScheme.primary
                                                : colorScheme.minor,
                                            overflow: TextOverflow.ellipsis,
                                          ).asExpanded(),
                                        ],
                                      ),
                                      for (var item
                                          in widget.contents ?? []) ...[
                                        if (item.children.length > 0) ...[
                                          Wisdom.row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            padding: EdgeInsets.fromLTRB(
                                                15.pt, 0, 0, 0),
                                            height: 38.pt,
                                            onTap: () => {
                                              changeFirstInventoryValue(
                                                  item.id),
                                              setInventorySecondList(
                                                  item.children),
                                            },
                                            color: inventoryFirstId == item.id
                                                ? Color.fromRGBO(
                                                    246, 247, 252, 1)
                                                : Colors.white,
                                            children: [
                                              if (inventoryFirstId ==
                                                  item.id) ...[
                                                Container(
                                                  height: 15.pt,
                                                  width: 3.pt,
                                                  color: colorScheme.primary,
                                                  margin: EdgeInsets.only(
                                                      right: 10.pt),
                                                ),
                                              ],
                                              WisText(
                                                item.label ?? '',
                                                size: 13.pt,
                                                color:
                                                    inventoryFirstId == item.id
                                                        ? colorScheme.primary
                                                        : colorScheme.minor,
                                                overflow: TextOverflow.ellipsis,
                                              ).asExpanded(),
                                            ],
                                          ),
                                        ]
                                      ],
                                    ],
                                  ),
                                ),
                                Wisdom(
                                  width: 1.pt,
                                  color: colorScheme.divider2,
                                ),
                                SingleChildScrollView(
                                  key: Key('taskHallFilterInner2'),
                                  child: Wisdom.column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      for (var i = 0;
                                          i < taskItemSecondList.length;
                                          i++) ...[
                                        Wisdom.row(
                                          padding: EdgeInsets.fromLTRB(
                                              15.pt, 0, 15.pt, 0),
                                          height: 38.pt,
                                          onTap: () => {
                                            changeSecondInventoryValue(
                                                taskItemSecondList[i]),
                                          },
                                          color: inventoryIds.length > 0 &&
                                                  inventoryIds.contains(
                                                      taskItemSecondList[i].id)
                                              ? Color.fromRGBO(246, 247, 252, 1)
                                              : Colors.white,
                                          children: [
                                            WisText(
                                              taskItemSecondList[i].label ?? '',
                                              size: 13.pt,
                                              color: inventoryIds.length > 0 &&
                                                      inventoryIds.contains(
                                                          taskItemSecondList[i]
                                                              .id)
                                                  ? colorScheme.primary
                                                  : colorScheme.minor,
                                              overflow: TextOverflow.ellipsis,
                                            ).asExpanded(),
                                            if (inventoryIds.length > 0 &&
                                                inventoryIds.contains(
                                                    taskItemSecondList[i]
                                                        .id)) ...[
                                              Image(
                                                image: AssetList.$xzh_png_image,
                                                width: 10.pt,
                                                height: 10.pt,
                                              ),
                                            ],
                                          ],
                                        ),
                                      ],
                                    ],
                                  ),
                                ).asExpanded(),
                              ],
                            )
                          ],
                          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,
    this.contents,
    this.checkList,
  }) : super(key: key);

  final item;
  final TextStyle? textStyle;
  final Function? onChange;
  final status;
  final List<TaskInventoryTreeModel>? contents;
  final List? checkList;

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    String? name = '';
    if (checkList != null && checkList!.length > 0) {
      name = checkList?.map((check) => check.label).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: [
          WisText(
            (checkList != null && checkList!.length > 0)
                ? '$name'
                : '${item.title}',
            color: (status == 'down' ||
                    (checkList != null && checkList!.length > 0))
                ? colorScheme.primary
                : colorScheme.mainTitle,
            size: textStyle?.fontSize ?? 15.pt,
            weight: textStyle?.fontWeight ?? FontWeight.w300,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
          if (item.hasIcon) ...[
            SizedBox(width: 5.pt),
            status == 'down' ? item.dropdownIcon : item.icon,
          ]
        ]).asExpanded();
  }
}

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

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