import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/index.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

/// 日期框
class PatientDateTime extends FStatefulWidget implements FPage {
  const PatientDateTime({
    Key? key,
    required this.context,
    required this.buildKey,
  }) : super(key: key);
  final BuildContext context;
  final String buildKey;

  @override
  FState<PatientDateTime> createState() => _PatientDateTimeState();

  @override
  String get pageName => 'PatientDateTime';
}

class _PatientDateTimeState extends FState<PatientDateTime> {
  late GlobalKey globalKey = GlobalKey(debugLabel: widget.buildKey);

  final controller = Get.find<AppointmentConsultationController>();

  String? appointmentTime;

  _findRenderObject(GlobalKey key) {
    RenderBox? renderBox = key.currentContext!.findRenderObject() as RenderBox;
    // offset.dx , offset.dy 就是控件的左上角坐标
    var offset = renderBox.localToGlobal(Offset.zero);
    return [offset.dx, offset.dy + 38];
  }

  @override
  void initState() {
    super.initState();
    setAppointmentTime();
  }

  void setAppointmentTime() {
    DateTime? timeOfAppointment =
        controller.state.appointmentInformation.appointmentTime;
    if (timeOfAppointment != null) {
      appointmentTime =
          DateFormat('yyyy-MM-dd').format(timeOfAppointment).toString();
    }
  }

  FCalendarDatePicker _calendarDatePicker(
    DatePickerMode mode,
    BuildContext context,
    String buildKey,
  ) {
    DateTime? initialDate =
        controller.state.appointmentInformation.appointmentTime;
    AppointmentInformations appointmentInformation =
        controller.state.appointmentInformation;
    return FCalendarDatePicker(
      initialDate: initialDate ?? DateTime.now(),
      firstDate: initialDate!.compareTo(DateTime.now()) == -1
          ? initialDate
          : DateTime.now(), // 开始日期 如果初始时间早于当前时间，则以初始时间作为开始时间
      lastDate: DateTime(3020, 10, 18), // 结束日期
      initialCalendarMode: mode, // 日期选择样式
      // 选中日期改变回调函数
      onDateChanged: (dateTime) {
        appointmentInformation.appointmentTime = dateTime.toLocal();
        setAppointmentTime();
        Navigator.of(context).pop();
        setState(() {});
      },
      // 月份改变回调函数
      onDisplayedMonthChanged: (dateTime) {},
      // 筛选日期可不可点回调函数
      selectableDayPredicate: (dayTime) {
        if (dayTime == DateTime(2020, 10, 15) ||
            dayTime == DateTime(2020, 10, 16) ||
            dayTime == DateTime(2020, 10, 17)) {
          return false;
        }
        return true;
      },
    );
  }

  FWidget dateTimeSelectionBox() {
    var startTimePosition = _findRenderObject(globalKey);

    return FGestureDetector(
      child: FStack(
        children: [
          FContainer(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
          ),
          FPositioned(
            top: startTimePosition[1],
            left: startTimePosition[0],
            child: FContainer(
              constraints: const BoxConstraints(
                maxWidth: 300,
                maxHeight: 400,
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                    blurRadius: 5,
                    color: Color(0xffeeeeee),
                  )
                ],
                borderRadius: BorderRadius.circular(5),
              ),
              child: _calendarDatePicker(
                DatePickerMode.day,
                context,
                widget.buildKey,
              ),
            ),
          ),
        ],
      ),
      onTap: () {
        Navigator.of(context).pop();
      },
      businessParent: widget,
      name: '',
    );
  }

  Future<void> openSelectTime() async {
    var date = await showDatePicker(
        context: this.context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        locale: i18nBook.locale,
        lastDate: DateTime(2050));
    if (date == null) return;
    controller.state.appointmentInformation.appointmentTime = date.toLocal();
    setAppointmentTime();
    setState(() {});
  }

  @override
  FWidget build(BuildContext context) {
    return FBorderInput(
      key: globalKey,
      hintSize: 16,
      contentSize: 16,
      maxLength: 20,
      onTap: () {
        openSelectTime();
      },
      readOnly: true,
      borderColor: const Color.fromRGBO(234, 234, 234, 1),
      controller: TextEditingController(
        text: appointmentTime,
      ),
      suffixIcon: FMaterial(
        color: Colors.transparent,
        child: FIconButton(
          onPressed: () {
            openSelectTime();
          },
          icon: const FIcon(
            Icons.date_range_rounded,
          ),
          businessParent: widget,
          name: '',
        ),
      ),
      height: 38,
      hintText: i18nBook.remedical.selectTime.t,
    );
  }
}
