import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/date_time.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/controller.dart';
import 'package:flyinsono/pages/remedical/create_check/state.dart';

import 'package:fis_theme/theme.dart';
import 'package:get/get.dart';

class FBuildAgeType extends FStatefulWidget {
  FBuildAgeType({
    this.appointmentFormEditing = false,
    Key? key,
  }) : super(key: key);

  /// 是否是编辑状态
  final bool appointmentFormEditing;
  @override
  FState<FBuildAgeType> createState() => _BuildAgeTypeState();
}

class _BuildAgeTypeState extends FState<FBuildAgeType> {
  final controller = Get.find<AppointmentConsultationController>();

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

  static const C_SPACING_WIDTH = 5.0;
  static const C_AGE_TYPE = [
    'Year',
    'YearAndMonth',
    'MonthAndWeek',
    'WeekAndDay',
  ];

  List<SelectModel> getAgeType() {
    List<SelectModel> selectList = [];
    for (int i = 0; i < C_AGE_TYPE.length; i++) {
      selectList.add(
        SelectModel(
          name: controller.realTimeConsultationController.getLanguageValues(
            'exam',
            C_AGE_TYPE[i],
          ),
          code: C_AGE_TYPE[i],
        ),
      );
    }
    return selectList;
  }

  @override
  FWidget build(BuildContext context) {
    return FRow(
      children: [
        FExpanded(
          child: FObx(
            () => _buildAgeType(
              controller.state.currentPatient.ageUnits,
            ),
          ),
        ),
        FExpanded(
          child: _buildAgeTypeSelect(),
        )
      ],
    );
  }

  FWidget _buildSizedBox() {
    return const FSizedBox(
      width: C_SPACING_WIDTH,
    );
  }

  FWidget _buildAgeType(String? currentAgeType) {
    switch (currentAgeType ?? 'Year') {
      case 'YearAndMonth':
        return _buildYearAndMonth();
      case 'MonthAndWeek':
        return _buildMonthAndWeek();
      case 'WeekAndDay':
        return _buildWeekAndDay();
      default:
        return _buildYear();
    }
  }

  FWidget _buildYear() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageUnits = 'Year';
              controller.state.currentPatient.ageYear = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(value);
            },
            controller.state.currentPatient.ageYear,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildYearAndMonth() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageYear = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(
                      value, controller.state.currentPatient.ageMonth ?? '');
            },
            controller.state.currentPatient.ageYear,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageMonth = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurYearAndMonthBirthDay(
                      controller.state.currentPatient.ageYear ?? '', value);
            },
            controller.state.currentPatient.ageMonth,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildMonthAndWeek() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageMonth = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurMonthAndWeekBirthDay(
                      value, controller.state.currentPatient.ageWeek ?? '');
            },
            controller.state.currentPatient.ageMonth,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageWeek = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurMonthAndWeekBirthDay(
                      controller.state.currentPatient.ageMonth ?? '', value);
            },
            controller.state.currentPatient.ageWeek,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([0-4])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildWeekAndDay() {
    return FContainer(
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageWeek = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurWeekAndDayBirthDay(
                      value, controller.state.currentPatient.ageDay ?? '');
            },
            controller.state.currentPatient.ageWeek,
            [FilteringTextInputFormatter.digitsOnly],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              controller.state.currentPatient.ageDay = value;
              controller.state.currentPatient.birthday =
                  FmtedDuration.countDurWeekAndDayBirthDay(
                      controller.state.currentPatient.ageWeek ?? '', value);
            },
            controller.state.currentPatient.ageDay,
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([1-9]|[1-2]\d|3[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.day.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildAgeTypeSelect() {
    void onSelectChanged(String? value, int? index) {
      PatientInfo currentPatient = controller.state.currentPatient;
      currentPatient.ageUnits = value;
      bool hasBirthDay = controller.state.currentPatient.birthday != null &&
          (controller.state.currentPatient.birthday?.isNotEmpty ?? false);
      switch (value ?? 'Year') {
        case 'YearAndMonth':
          if (hasBirthDay) {
            currentPatient.ageYear = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageMonth = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }

          break;
        case 'MonthAndWeek':
          if (hasBirthDay) {
            currentPatient.ageMonth = FmtedDuration.countDurMonthAndWeek(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageWeek = FmtedDuration.countDurMonthAndWeek(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }
          break;
        case 'WeekAndDay':
          if (hasBirthDay) {
            currentPatient.ageWeek = FmtedDuration.countDurWeekAndDay(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
            currentPatient.ageDay = FmtedDuration.countDurWeekAndDay(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[1]
                .toString();
          }
          break;
        default:
          if (hasBirthDay) {
            currentPatient.ageYear = FmtedDuration.countDurYearAndMonth(
              DateTime.parse(
                currentPatient.birthday!,
              ),
            )[0]
                .toString();
          }
          break;
      }
      setState(() {});
    }

    final select = FObx(() {
      String ageUnits = controller.state.currentPatient.ageUnits ?? 'Year';
      if (ageUnits.isEmpty) {
        ageUnits = 'Year';
      }
      return FSelect<SelectModel, String>(
        source: getAgeType(),
        value: ageUnits,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        clearable: false,
        height: 38,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          onSelectChanged(value, index);
        },
      );
    });
    return FObx(() {
      if (controller.state.isAddPatient || widget.appointmentFormEditing) {
        return select;
      } else {
        return const FSizedBox();
      }
    });
  }

  FWidget _buildAgeTypeInput(Function(dynamic)? onChanged, String? text,
      [List<TextInputFormatter>? inputFormatters]) {
    print(widget.appointmentFormEditing);
    return FBorderInput(
      maxLength: 20,
      borderColor: const Color.fromRGBO(230, 230, 230, 1),
      height: 38,
      contentSize: 16,
      enabled: (controller.state.isAddPatient || widget.appointmentFormEditing)
          ? true
          : false,
      onChanged: (value) => onChanged?.call(value),
      controller: TextEditingController(
        text: text,
      ),
      inputFormatters: inputFormatters,
    );
  }
}
