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/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/create_check/state.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';
import 'package:fis_theme/theme.dart';

class BuildAgeType extends FStatefulWidget {
  BuildAgeType({Key? key, required this.ageType}) : super(key: key);

  final Map<String, dynamic> ageType;
  @override
  FState<BuildAgeType> createState() => _BuildAgeTypeState();
}

class _BuildAgeTypeState extends FState<BuildAgeType> {
  final consultationController = Get.find<ConsultationController>();
  final controller = Get.find<AddoreditPatientDialogController>();
  final fmtedDuration = Get.find<FmtedDuration>();
  bool get birthDayIsNull =>
      controller.patientInfo['Birthday'] != null &&
      controller.patientInfo['Birthday'] != '';

  @override
  void initState() {
    super.initState();
    fmtedDuration.isChangeTimeChanged.addListener((sender, e) {
      setState(() {});
    });
  }

  @override
  FWidget build(BuildContext context) {
    return FExpanded(
      child: FRow(
        children: [
          _buildAgeType(),
          _buildAgeTypeSelect(
            widget.ageType['Source'],
            widget.ageType['key'],
          ),
        ],
      ),
    );
  }

  void _clearState() {
    controller.patientInfo['AgeYear'] = null;
    controller.patientInfo['AgeMonth'] = null;
    controller.patientInfo['AgeWeek'] = null;
    controller.patientInfo['AgeDay'] = null;
  }

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

  FWidget _buildAgeType() {
    switch (controller.patientInfo['AgeUnits'] ?? 'Year') {
      case 'YearAndMonth':
        return _buildYearAndMonth();
      case 'MonthAndWeek':
        return _buildMonthAndWeek();
      case 'WeekAndDay':
        return _buildWeekAndDay();
      default:
        return _buildYear();
    }
  }

  FWidget _buildYear() {
    _initYearData();

    return FContainer(
      width: 180,
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurYearAndMonthBirthDay(value);
              } catch (e) {}
              controller.patientInfo['AgeUnits'] = 'Year';
              controller.patientInfo['AgeYear'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeYear'],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildYearAndMonth() {
    _initYearAndMonthData();
    return FContainer(
      width: 180,
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurYearAndMonthBirthDay(
                  value,
                  controller.patientInfo['AgeMonth'],
                );
              } catch (e) {}

              controller.patientInfo['AgeYear'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeYear'],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.years.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              controller.patientInfo['Birthday'] =
                  FmtedDuration.countDurYearAndMonthBirthDay(
                controller.patientInfo['AgeYear'],
                value,
              );
              controller.patientInfo['AgeMonth'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeMonth'],
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildMonthAndWeek() {
    _initMonthAndWeekData();
    return FContainer(
      width: 180,
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurMonthAndWeekBirthDay(
                  value,
                  controller.patientInfo['AgeWeek'],
                );
              } catch (e) {}

              controller.patientInfo['AgeMonth'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeMonth'],
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^(0?[1-9]|1[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.month.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurMonthAndWeekBirthDay(
                  controller.patientInfo['AgeMonth'],
                  value,
                );
              } catch (e) {}

              controller.patientInfo['AgeWeek'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeWeek'],
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([0-4])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildWeekAndDay() {
    _initWeekAndDayData();
    return FContainer(
      width: 180,
      child: FRow(
        children: [
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurWeekAndDayBirthDay(
                  value,
                  controller.patientInfo['AgeDay'],
                );
              } catch (e) {}
              controller.patientInfo['AgeWeek'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeWeek'],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.week.t),
          _buildSizedBox(),
          _buildAgeTypeInput(
            (value) {
              try {
                controller.patientInfo['Birthday'] =
                    FmtedDuration.countDurWeekAndDayBirthDay(
                  controller.patientInfo['AgeWeek'],
                  value,
                );
              } catch (e) {}
              controller.patientInfo['AgeDay'] = value;
              fmtedDuration.isChangeBirth = !fmtedDuration.isChangeBirth;
              _setEditBirthDay();
            },
            controller.patientInfo['AgeDay'],
            [
              FilteringTextInputFormatter.allow(
                RegExp(r'^([1-9]|[1-2]\d|3[0-1])$'),
              ),
            ],
          ),
          _buildSizedBox(),
          FText(i18nBook.remedical.day.t),
          _buildSizedBox(),
        ],
      ),
    );
  }

  FWidget _buildAgeTypeSelect(List list, String key) {
    List<SelectModel> selectList = [];
    list.forEach(
      (element) {
        selectList.add(
          SelectModel(
            code: element,
            name: consultationController.getValues(element),
          ),
        );
      },
    );

    void onSelectChanged(String? value, int? index) {
      _clearState();
      [controller.patientInfo, controller.editPatientInfo]
          .forEach((info) => info['AgeUnits'] = value);
      fmtedDuration.isChangeTime = !fmtedDuration.isChangeTime;
      setState(() {});
    }

    final select = FSelect<SelectModel, String>(
      source: selectList,
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      value: controller.patientInfo['AgeUnits'] == ''
          ? 'Year'
          : controller.patientInfo['AgeUnits'] ?? 'Year',
      clearable: false,
      height: 38,
      optionLabelExtractor: (data) => data.name,
      optionValueExtractor: (data) => data.code,
      onSelectChanged: (value, index) {
        onSelectChanged(value, index);
      },
    );

    return FExpanded(
      child: select,
    );
  }

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

  /// 初始化年数据
  void _initYearData() {
    if (birthDayIsNull) {
      final ageYear = FmtedDuration.countDurYearAndMonth(
        DateTime.parse(controller.patientInfo['Birthday']),
      )[0]
          .toString();
      controller.patientInfo['AgeYear'] = ageYear;
      controller.editPatientInfo['AgeYear'] = ageYear;
    } else {
      controller.patientInfo['AgeUnits'] =
          controller.editPatientInfo['AgeUnits'] = 'Year';
    }
  }

  /// 初始化年月数据
  void _initYearAndMonthData() {
    if (birthDayIsNull) {
      final age = FmtedDuration.countDurYearAndMonth(
        DateTime.parse(controller.patientInfo['Birthday']),
      );
      controller.patientInfo
        ..['AgeYear'] = age[0].toString()
        ..['AgeMonth'] = age[1].toString();
      controller.editPatientInfo
        ..['AgeYear'] = age[0].toString()
        ..['AgeMonth'] = age[1].toString();
    }
  }

  /// 初始化月周数据
  void _initMonthAndWeekData() {
    if (birthDayIsNull) {
      final age = FmtedDuration.countDurMonthAndWeek(
        DateTime.parse(controller.patientInfo['Birthday']),
      );
      controller.patientInfo
        ..['AgeMonth'] = age[0].toString()
        ..['AgeWeek'] = age[1].toString();
      controller.editPatientInfo
        ..['AgeMonth'] = age[0].toString()
        ..['AgeWeek'] = age[1].toString();
    }
  }

  /// 初始化周天数据
  void _initWeekAndDayData() {
    if (birthDayIsNull) {
      final age = FmtedDuration.countDurWeekAndDay(
        DateTime.parse(controller.patientInfo['Birthday']),
      );
      controller.patientInfo
        ..['AgeWeek'] = age[0].toString()
        ..['AgeDay'] = age[1].toString();
      controller.editPatientInfo
        ..['AgeWeek'] = age[0].toString()
        ..['AgeDay'] = age[1].toString();
    }
  }

  void _copyPatientInfo(String key) {
    controller.editPatientInfo[key] = controller.patientInfo[key];
  }

  /// 设置编辑月份
  void _setEditBirthDay() {
    _copyPatientInfo('Birthday');
    _copyPatientInfo('AgeUnits');
    _copyPatientInfo('AgeYear');
    _copyPatientInfo('AgeMonth');
    _copyPatientInfo('AgeWeek');
    _copyPatientInfo('AgeDay');
  }
}
