import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/controller.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/date_time.dart';
import 'package:get/get.dart';

/// 日期框
class PatientItemDateTime extends FStatefulWidget
    implements FInteractiveContainer {
  PatientItemDateTime({
    Key? key,
    required this.context,
    required this.buildKey,
    this.pageName = 'PatientItemDateTime',
  }) : super(key: key);
  final BuildContext context;
  final String buildKey;
  @override
  final String pageName;

  @override
  FState<PatientItemDateTime> createState() => _PatientItemDateTimeState();
}

class _PatientItemDateTimeState extends FState<PatientItemDateTime> {
  late String birthday = '';
  late GlobalKey globalKey = GlobalKey(debugLabel: widget.buildKey);

  final controller = Get.find<AddoreditPatientDialogController>();
  final fmtedDuration = Get.find<FmtedDuration>();

  _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();
    fmtedDuration.isChangeBirthChanged.addListener((sender, e) {
      setState(() {});
    });
  }

  FCalendarDatePicker _calendarDatePicker(
    DatePickerMode mode,
    BuildContext context,
    String buildKey,
  ) {
    String initDate = controller.patientInfo[buildKey] == ''
        ? DateTime.now().toString()
        : controller.patientInfo[buildKey] ?? DateTime.now().toString();
    return FCalendarDatePicker(
      initialDate: DateTime.parse(
        initDate,
      ),
      // 初始化选中日期
      // currentDate: DateTime(2020, 10, 18),
      firstDate: DateTime(1920, 9, 10), // 开始日期
      lastDate: DateTime.now(), // 结束日期
      initialCalendarMode: mode, // 日期选择样式
      // 选中日期改变回调函数
      onDateChanged: (dateTime) async {
        Navigator.of(context).pop();
        birthday = dateTime.toString().split(' ')[0];
        controller.patientInfo[buildKey] = birthday;
        controller.editPatientInfo[buildKey] = birthday;

        setState(() {});
        fmtedDuration.isChangeTime = !fmtedDuration.isChangeTime;
      },
      // 月份改变回调函数
      onDisplayedMonthChanged: (dateTime) {},
      // 筛选日期可不可点回调函数
      selectableDayPredicate: (dayTime) {
        if (dayTime == DateTime(2020, 10, 15) ||
            dayTime == DateTime(2020, 10, 16) ||
            dayTime == DateTime(2020, 10, 17)) {
          return false;
        }
        return true;
      },
    );
  }

  void openSelectTime() {
    print(widget.buildKey);
    print(controller.patientInfo[widget.buildKey]);
    var startTimePosition = _findRenderObject(globalKey);
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return FGestureDetector(
          name: "openSelectTime",
          businessParent: widget,
          child: FStack(
            children: [
              FContainer(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                // color: Colors.transparent, // 它的颜色为透明色
              ),
              FPositioned(
                top: MediaQuery.of(context).size.height - startTimePosition[1] >
                        400
                    ? startTimePosition[1]
                    : startTimePosition[1] - 380,
                left: startTimePosition[0],
                child: FContainer(
                  // margin: EdgeInsets.only(left: 16, top: 12),
                  constraints: BoxConstraints(
                    maxWidth: 310,
                    maxHeight: 400,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        blurRadius: 5,
                        color: Color(0xffeeeeee),
                      )
                    ],
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: _calendarDatePicker(
                    DatePickerMode.day,
                    context,
                    widget.buildKey,
                  ),
                ),
              ),
            ],
          ),
          onTap: () {
            Navigator.of(context).pop();
          },
        );
      },
    );
  }

  @override
  FWidget build(BuildContext context) {
    return FBorderInput(
      key: globalKey,
      hintSize: 16,
      contentSize: 16,
      maxLength: 20,
      onTap: () {
        openSelectTime();
      },
      // enabled: controller.state.isEditStatus ? false : true,
      borderColor: Color.fromRGBO(234, 234, 234, 1),
      controller: controller.getControllerByKey(
        widget.buildKey,
        value: controller.patientInfo[widget.buildKey] ?? '',
      ),
      suffixIcon: FMaterial(
        color: Colors.transparent,
        child: FIconButton(
          name: "openSelectTime",
          businessParent: widget,
          onPressed: () {
            openSelectTime();
          },
          icon: FIcon(
            Icons.date_range_rounded,
          ),
        ),
      ),
      height: 38,
      hintText: i18nBook.remedical.selectTime.t,
    );
  }
}
