/*
 * @Author: XianKaiQun
 * @Date: 2020-08-06 11:44:57
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-16 10:13:55
 * @Description: 
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

final _shape = RoundedRectangleBorder(
  borderRadius: BorderRadius.only(
    topLeft: Radius.circular(10.pt),
    topRight: Radius.circular(10.pt),
  ),
);

class WisBottomModalUtil {
  ///弹层；
  static Future<T?> show<T>(
    BuildContext context, {
    bool? disabledConfirm,
    bool plain = true,
    BoxConstraints bodyConstraints =
        const BoxConstraints(maxHeight: 350, minHeight: 250),
    String? title,
    String confirmText = '确定',
    String cancelText = '取消',
    void Function(BuildContext)? onConfirm,
    void Function(BuildContext)? onCancel,
    Widget? body,
  }) {
    return showModalBottomSheet<T>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (_) => WisBottomModalLayout(
        plain: plain,
        bodyConstraints: bodyConstraints,
        title: title,
        onConfirm: onConfirm,
        onCancel: onCancel,
        confirmText: confirmText,
        cancelText: cancelText,
        body: body,
      ),
    );
  }

  ///单选
  static Future<T?> showPicker<@required T>(
    BuildContext context, {
    String? title,
    required Future<List<T>> getData,
    required String Function(T) name,
    required dynamic Function(T) unique,
    T? select,
  }) {
    return showModalBottomSheet<T>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (context) {
        List<T> _selects = [];

        if (select != null) _selects = [select];

        void onChanged(List<T>? selects, bool? isTap) {
          _selects = selects!;
          if (isTap!) Navigator.pop(context, _selects[0]);
        }

        return WisBottomModalLayout(
          title: title,
          plain: true,
          body: WisPicker<T>(
            multiple: false,
            selects: _selects,
            getData: getData,
            name: name,
            unique: unique,
            onChanged: onChanged,
          ),
        );
      },
    );
  }

  ///多选
  static Future<List<T>?> showMultiplePicker<@required T>(
    BuildContext context, {
    bool? disabledConfirm,
    required Future<List<T>> getData,
    required String Function(T) name,
    required dynamic Function(T) unique,
    List<T>? selects = const [],
  }) {
    return showModalBottomSheet<List<T>>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (context) {
        List<T> _selects = selects ?? [];
        void onCancel(context) => Navigator.pop(context);
        void onConfirm(context) {
          if (_selects.length != 0) Navigator.pop(context, _selects);
        }

        return WisBottomModalLayout(
          plain: false,
          onCancel: onCancel,
          onConfirm: onConfirm,
          body: WisPicker<T>(
            multiple: true,
            selects: _selects,
            getData: getData,
            name: name,
            unique: unique,
            onChanged: (selects, _) {
              _selects = selects!;
            },
          ),
        );
      },
    );
  }

  ///无限单选
  static Future<List<T>?> showInfinityPicker<@required T>(
    BuildContext context, {
    bool? disabledConfirm,
    String? title,
    required Future<List<T>> Function(T? item) getData,
    required String Function(T?) name,
    required dynamic Function(T?) unique,
    required Future<bool> Function(List<T?>) isLast,
    List<T> selects = const [],
  }) {
    return showModalBottomSheet<List<T>>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (context) {
        List<T?> _selects = selects;
        int index = (_selects.length - 1 < 0) ? 0 : selects.length - 1;
        bool showFutrue = _selects.length == 0;
        T? parentValue() {
          if (_selects.length == 0 || index == 0) {
            return null;
          } else {
            return _selects[index - 1];
          }
        }

        T? currentValue() {
          if (index >= _selects.length) {
            return null;
          } else {
            return _selects[index];
          }
        }

        void onCancel(context) => Navigator.pop(context);
        void onConfirm(context) {
          if (_selects.length != 0) Navigator.pop(context, _selects);
        }

        return WisBottomModalLayout(
          plain: true,
          onCancel: onCancel,
          title: title,
          onConfirm: onConfirm,
          body: StatefulBuilder(
            builder: (BuildContext context, setState) {
              add(List<T?> items, isTap) async {
                if (isTap) {
                  showFutrue = true;
                  if (index <= _selects.length - 1) {
                    _selects.removeRange(index, _selects.length);
                  }
                  index++;
                  _selects.add(items[0]);

                  setState(() {});
                  if (await isLast(_selects) == true) {
                    onConfirm(context);
                  }
                }
              }

              behind(int i) {
                index = i;
                setState(() {});
              }

              Widget tab(i) {
                String text =
                    (_selects.length > i) ? '${name(_selects[i])}' : '请选择';
                return Wisdom.column(
                  onTap: () => behind(i),
                  maxWidth: 100,
                  mainAxisAlignment: MainAxisAlignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 10),
                  children: [
                    Text(
                      text,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: 12.pt),
                    ),
                    SizedBox(
                      height: 5.pt,
                      child: (i == index)
                          ? WisActiveness(margin: EdgeInsets.only(top: 2))
                          : null,
                    ),
                  ],
                );
              }

              Widget tabs() {
                return SizedBox(
                  height: 40,
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: [
                      if (showFutrue)
                        for (var i = 0; i < _selects.length + 1; i++) tab(i)
                      else
                        for (var i = 0; i < _selects.length; i++) tab(i),
                    ],
                  ),
                );
              }

              return Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  tabs(),
                  Divider(height: 1),
                  WisPicker<T?>(
                    key: UniqueKey(),
                    multiple: false,
                    selects: currentValue() == null ? [] : [currentValue()],
                    getData: getData(parentValue()),
                    name: name,
                    unique: unique,
                    onChanged: (selects, isTap) => add(selects!, isTap),
                  ).asExpanded(),
                ],
              );
            },
          ),
        );
      },
    );
  }

  ///月份选择
  /// TODO:
  static Future<DateTime?> showMonthPicker(
    BuildContext context, {
    String title = '月份选择',
    bool? disabledConfirm,
    DateTime? firstDate,
    DateTime? lastDate,
    DateTime? selectedDate,
  }) {
    return showModalBottomSheet<DateTime>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (context) {
        final _firstDate = firstDate ?? DateTime(2015);
        DateTime _selectedDate = selectedDate ?? DateTime.now();
        DateTime _lastDate = lastDate ?? DateTime.now();

        return WisBottomModalLayout(
          title: title,
          plain: false,
          onCancel: (_) => Navigator.pop(context),
          onConfirm: (_) => Navigator.pop(context, _selectedDate),
          body: StatefulBuilder(
            builder: (BuildContext context, setState) {
              return CalendarDatePicker(
                firstDate: _firstDate,
                lastDate: _lastDate,
                initialDate: _selectedDate,
                onDateChanged: (DateTime value) {
                  _selectedDate = value;
                  setState(() {});
                },
              );
            },
          ),
        );
      },
    );
  }

  ///简易单选
  static Future<T?> showPickerSingle<@required T>(
    BuildContext context, {
    String? title,
    bool? disabledConfirm,
    bool? dense,
    required List<T> getData,
    required String Function(T) name,
    required dynamic Function(T) unique,
    T? select,
    void Function(List<T> selects, bool isTap)? onChanged,
  }) {
    return showModalBottomSheet<T>(
      shape: _shape,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      context: context,
      builder: (context) {
        // List<T> _selects = [];

        // if (select != null) _selects = [select];

        // void onChanged(List<T> selects, bool isTap) {
        //   _selects = selects;
        //   if (isTap) Navigator.pop(context, _selects[0]);
        // }

        return WisBottomModalLayout(
          title: title,
          plain: true,
          // body: WisPicker<T>(
          //   multiple: false,
          //   selects: _selects,
          //   getData: getData,
          //   name: name,
          //   unique: unique,
          //   onChanged: onChanged,
          // ),
        );
      },
    );
  }
}
