/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-04-01 10:11:34
 * @LastEditTime : 2023-05-25 15:49:28
 * @FilePath     : /wisdom-huiguanjia-app/wisdom_cli/lib/src/form_widget/components/time_range_picker.dart
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:intl/intl.dart';

class WFTimeRangePicker extends StatelessWidget {
  const WFTimeRangePicker({
    Key? key,
    this.title,
    this.isRequired = false,
    this.hintText,
    this.onChanged,
    this.initialTime,
    this.initialStartTime,
    this.initialEndTime,
    this.minimumTime,
    this.maximumTime,
    this.mode,
  }) : super(key: key);
  final DateTime? initialStartTime;
  final DateTime? initialEndTime;
  final DateTime? minimumTime;
  final DateTime? maximumTime;
  final DateTimeRangePickerMode? mode;
  final List? initialTime;
  final Widget? title;

  ///是否必须
  final bool isRequired;
  final String? hintText;
  final void Function(List? datetime)? onChanged;

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    List? _initialTime = initialTime ?? [];

    return WisFormLayoutComponent(
      title: title,
      isRequired: isRequired,
      axis: Axis.horizontal,
      child: StatefulBuilder(
        builder: (BuildContext context, setState) {
          return Row(
            children: [
              Wisdom.row(
                  onTap: () {
                    DateTimeRangePicker(
                        startText: "开始",
                        endText: "结束",
                        doneText: "确定",
                        cancelText: "取消",
                        interval: 5,
                        initialStartTime: _initialTime!.length > 0
                            ? DateTime(
                                DateTime.now().year,
                                DateTime.now().month,
                                DateTime.now().day,
                                int.parse(_initialTime![0].split(':')[0]),
                                int.parse(_initialTime![0].split(':')[1]),
                              )
                            : DateTime.now(),
                        initialEndTime: _initialTime!.length > 0
                            ? DateTime(
                                DateTime.now().year,
                                DateTime.now().month,
                                DateTime.now().day,
                                int.parse(_initialTime![1].split(':')[0]),
                                int.parse(_initialTime![1].split(':')[1]),
                              )
                            : DateTime.now(),
                        mode: mode,
                        minimumTime: DateTime.now().subtract(Duration(days: 1)),
                        maximumTime: DateTime.now().add(Duration(days: 1)),
                        use24hFormat: true,
                        onConfirm: (start, end) {
                          final DateFormat outputFormat = DateFormat("HH:mm");
                          List arr = [];
                          arr.add(
                            outputFormat.format(
                              start!,
                            ),
                          );
                          arr.add(
                            outputFormat.format(
                              end!,
                            ),
                          );
                          if (start.isAfter(end)) {
                            WToastUtil.show('结束时间需小于开始时间！');
                            return;
                          }
                          if (start.isBefore(end) && onChanged != null)
                            onChanged!(arr);
                        }).showPicker(context);
                  },
                  children: [
                    _initialTime != null && _initialTime!.length > 0
                        ? Text(
                            _initialTime!.join('至'),
                            style: TextStyle(
                              color: colorScheme.mainTitle,
                              fontWeight: FontWeight.w600,
                            ),
                          )
                        : Text(
                            hintText ?? '',
                            style: TextStyle(
                              color: colorScheme.placeholder,
                              fontSize: 14.pt,
                              fontWeight: FontWeight.w300,
                            ),
                          )
                  ]).asExpanded(),
              // TextField(
              //   controller: TextEditingController(
              //     text: _initialTime != null && _initialTime.length > 0
              //         ? _initialTime.join('至')
              //         : '  ',
              //   ),
              //   readOnly: true,

              //   style: TextStyle(
              //     fontSize: 15.pt,
              //     fontWeight: FontWeight.w600,
              //     color: colorScheme.text,
              //   ),
              //   decoration: InputDecoration(
              //     fillColor: Colors.transparent,
              //     filled: true,
              //     hintText: hintText,
              //     hintStyle: TextStyle(
              //       fontSize: 14.pt,
              //       color: colorScheme.placeholder,
              //       fontWeight: FontWeight.w300,
              //     ),
              //   ),
              // ).asExpanded(),
              _initialTime != null && _initialTime!.length > 0
                  ? WFClose(
                      onTap: () {
                        _initialTime = null;
                        setState(() {});
                        if (onChanged != null) onChanged!(null);
                      },
                    )
                  : Icon(
                      FaIcons.angle_right,
                      size: 18.pt,
                      color: colorScheme.placeholder,
                    )
            ],
          );
        },
      ),
    );
  }
}

typedef PickerConfirmCallback = Function(DateTime? start, DateTime? end);

enum DateTimeRangePickerMode {
  time,
  date,
  dateAndTime,
}

class DateTimeRangePicker {
  final startText;
  final endText;
  final doneText;
  final cancelText;
  final bool use24hFormat;
  final DateTimeRangePickerMode? mode;

  DateTime? initialStartTime;
  DateTime? initialEndTime;
  DateTime? minimumTime;
  DateTime? maximumTime;

  final VoidCallback? onCancel;
  final PickerConfirmCallback? onConfirm;

  final int interval;

  DateTimeRangePicker(
      {Key? key,
      this.onCancel,
      this.onConfirm,
      this.startText = "开始时间",
      this.endText = "结束时间",
      this.doneText = "完成",
      this.cancelText = "取消",
      this.initialStartTime,
      this.initialEndTime,
      this.mode = DateTimeRangePickerMode.dateAndTime,
      this.minimumTime,
      this.maximumTime,
      this.interval = 1,
      this.use24hFormat = false});

  void showPicker(BuildContext context) {
    if (initialStartTime == null) {
      initialStartTime = DateTime.now();
    }

    // Remove minutes and seconds to prevent exception of cupertino picker: initial minute is not divisible by minute interval
    // initialStartTime = initialStartTime.subtract(Duration(

    //     hours: initialStartTime.hour,
    //     minutes: initialStartTime.minute,
    //     seconds: initialStartTime.second));

    if (initialEndTime == null) {
      initialStartTime = DateTime.now();
      // initialEndTime = initialStartTime.add(Duration(
      //     days: mode == DateTimeRangePickerMode.time ? 0 : 1,
      //     hours: mode == DateTimeRangePickerMode.time ? 2 : 0));
    }

    // initialEndTime = initialEndTime.subtract(Duration(
    //     minutes: initialEndTime.minute, seconds: initialEndTime.second));

    if (minimumTime != null) {
      minimumTime = minimumTime!.subtract(
          Duration(minutes: minimumTime!.minute, seconds: minimumTime!.second));
    }

    if (maximumTime != null) {
      maximumTime = maximumTime!.subtract(
          Duration(minutes: maximumTime!.minute, seconds: maximumTime!.second));
    }

    var pickerMode = CupertinoDatePickerMode.dateAndTime;

    switch (mode) {
      case DateTimeRangePickerMode.date:
        {
          pickerMode = CupertinoDatePickerMode.date;
        }
        break;

      case DateTimeRangePickerMode.time:
        {
          pickerMode = CupertinoDatePickerMode.time;
        }
        break;

      default:
        {
          pickerMode = CupertinoDatePickerMode.dateAndTime;
        }
        break;
    }

    showDialog(
        context: context,
        builder: (BuildContext context) {
          return FractionallySizedBox(
            widthFactor: 0.8,
            heightFactor: 0.5,
            child: PickerWidget([
              Tab(text: startText),
              Tab(text: endText),
            ],
                initialStartTime,
                initialEndTime,
                interval,
                this.onCancel,
                this.onConfirm,
                pickerMode,
                this.doneText,
                this.cancelText,
                this.minimumTime,
                this.maximumTime,
                this.use24hFormat),
          );
        });
  }
}

class PickerWidget extends StatefulWidget {
  final List<Tab> _tabs;
  // ignore: unused_field
  final int _interval;
  final VoidCallback? _onCancel;
  final PickerConfirmCallback? _onConfirm;

  final DateTime? _initStart;
  final DateTime? _initEnd;
  final CupertinoDatePickerMode _mode;

  final String _doneText;
  final String _cancelText;
  final DateTime? _minimumTime;
  final DateTime? _maximumTime;
  final bool _use24hFormat;

  PickerWidget(
      this._tabs,
      this._initStart,
      this._initEnd,
      this._interval,
      this._onCancel,
      this._onConfirm,
      this._mode,
      this._doneText,
      this._cancelText,
      this._minimumTime,
      this._maximumTime,
      this._use24hFormat,
      {Key? key})
      : super(key: key);

  _PickerWidgetState createState() => _PickerWidgetState();
}

class _PickerWidgetState extends State<PickerWidget>
    with SingleTickerProviderStateMixin {
  TabController? _tabController;
  DateTime? _start;
  DateTime? _end;

  @override
  void initState() {
    super.initState();
    _start = widget._initStart;
    _end = widget._initEnd;

    _tabController = TabController(vsync: this, length: widget._tabs.length);
  }

  @override
  void dispose() {
    _tabController!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          title: Container(
            child: TabBar(
              dividerHeight: 0,
              controller: _tabController,
              tabs: widget._tabs,
              labelColor: Theme.of(context).primaryColor,
            ),
          ),
        ),
        body: Stack(
          children: <Widget>[
            Container(
              height: 320,
              alignment: Alignment.topCenter,
              child: TabBarView(
                controller: _tabController,
                children: widget._tabs.map((Tab tab) {
                  return CupertinoDatePicker(
                    mode: widget._mode,
                    use24hFormat: widget._use24hFormat,
                    minuteInterval: 1,
                    minimumDate: widget._minimumTime != null &&
                            tab.text == widget._tabs.first.text
                        ? widget._minimumTime
                        : null,
                    maximumDate: widget._maximumTime != null &&
                            tab.text == widget._tabs.last.text
                        ? widget._maximumTime
                        : null,
                    initialDateTime:
                        tab.text == widget._tabs.first.text ? _start : _end,
                    onDateTimeChanged: (DateTime newDateTime) {
                      if (tab.text == widget._tabs.first.text) {
                        setState(() {
                          _start = newDateTime;
                        });
                      } else {
                        setState(() {
                          _end = newDateTime;
                        });
                      }
                    },
                  );
                }).toList(),
              ),
            ),
            Container(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                      if (widget._onCancel != null) {
                        widget._onCancel!();
                      }
                    },
                    child: Text(widget._cancelText),
                  ),
                  TextButton(
                    onPressed: () {
                      if (_start!.isAfter(_end!)) {
                        WToastUtil.show('结束时间需大于开始时间！');
                        return;
                      }
                      Navigator.of(context).pop();
                      if (widget._onConfirm != null) {
                        widget._onConfirm!(_start, _end);
                      }
                    },
                    child: Text(widget._doneText),
                  )
                ],
              ),
            )
          ],
        ));
  }
}
