import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/widgets/checkbox/rectangle_checkbox.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.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/widgets/date_time.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/patient_item_age_type.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/patient_item_date_time.dart';
import 'package:flyinsono/pages/upload/image_upload_card.dart';
import 'package:get/get.dart';

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

///新增或编辑病人对话框
class AddoreditPatientDialogPage
    extends FisView<AddoreditPatientDialogController> implements FPage {
  const AddoreditPatientDialogPage(
      {this.pageName = 'AddoreditPatientDialogPage', Key? key})
      : super(key: key);
  @override
  final String pageName;
  @override
  FWidget build(BuildContext context) {
    final page = context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
    return page;
  }
}

class _DesktopLayout extends FStatefulWidget {
  _DesktopLayout(this.businessParent, {Key? key}) : super(key: key);

  ///父级节点
  final FPage businessParent;
  @override
  FState<_DesktopLayout> createState() => _DesktopLayoutState();
}

class _DesktopLayoutState extends FState<_DesktopLayout> {
  final consultationController = Get.find<ConsultationController>();
  final controller = Get.find<AddoreditPatientDialogController>();
  final fmtedDuration = Get.put(FmtedDuration());

  @override
  FWidget build(BuildContext context) {
    final addOrEditPatint = FContainer(
      color: Colors.white,
      padding: EdgeInsets.only(top: 40, left: 20, right: 45),
      child: FGridView(
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, //横轴三个子widget
          childAspectRatio: 6, //子widget宽高比例
        ),
        children: [
          ...controller.patientKeyList.map((e) {
            if (e['ShowType'] == 'select') {
              return _buildItemRow(
                consultationController.getValues(e['key']),
                _buildSelect(e['Source'], e['key']),
                isRequired: e['Required'] ?? false,
              );
            } else if (e['ShowType'] == 'datetime') {
              return _buildItemRow(
                consultationController.getValues(e['key']),
                PatientItemDateTime(
                  context: context,
                  buildKey: e['key'],
                ),
                isRequired: e['Required'] ?? false,
              );
            } else if (e['ShowType'] == 'AgeType') {
              return _buildItemRow(
                consultationController.getValues(e['key']),
                BuildAgeType(
                  ageType: e,
                ),
                isRequired: e['Required'] ?? false,
                isShowTitle: false,
              );
            } else {
              return _buildItemRow(
                consultationController.getValues(e['key']),
                _buildPatientInfoInput(e),
                isRequired: e['Required'] ?? false,
              );
            }
          }).toList(),
        ],
      ),
    );

    return AddOrEditPatientDiaLog(
      addOrEditPatient: addOrEditPatint,
      addOrEditPatientAvatar: _buildAddOrEditPatienAvatarTemplate(),
      autoCreateDiagnosisFlag: _buildAutoCreateDiagnosisTemplate(),
    );
  }

  FWidget _buildAddOrEditPatienAvatarTemplate() {
    return FContainer(
      color: Colors.white,
      padding: EdgeInsets.only(
        top: 20,
        left: 20,
        right: 45,
        bottom: 30,
      ),
      child: FGridView(
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1, //横轴三个子widget
          /// TODO:[Gavin] 多语言-UI-整合
          childAspectRatio: i18nBook.isCurrentChinese ? 7 : 10, //子widget宽高比例
        ),
        children: [
          _buildItemRow(
            i18nBook.common.photo.t,
            FExpanded(
              child: FRow(
                children: [
                  FContainer(
                    child: ImageUploadCard(
                      originImgUrl: consultationController
                                  .patientInfoController.patientType ==
                              OrganizationPatientTypeEnum.Person
                          ? controller.patientInfo['HeadImgUrl']
                          : controller.patientInfo['AnimalInfoHeadImgUrl'],
                      onUploaded: (url) {
                        Future.microtask(() {
                          consultationController
                                      .patientInfoController.patientType ==
                                  OrganizationPatientTypeEnum.Person
                              ? {
                                  controller.patientInfo['HeadImgUrl'] = url,
                                  controller.editPatientInfo['HeadImgUrl'] = url
                                }
                              : {
                                  controller
                                          .patientInfo['AnimalInfoHeadImgUrl'] =
                                      url,
                                  controller.editPatientInfo[
                                      'AnimalInfoHeadImgUrl'] = url
                                };
                        });
                      },
                      hintText: "",
                      width: 120,
                      isShowAddIcon: true,
                    ),
                  ),
                  FExpanded(child: FContainer())
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildItemRow(String title, FWidget widget,
      {bool isRequired = false, bool isShowTitle = true}) {
    final labelStyle = TextStyle(fontSize: 16);
    return FContainer(
      width: 30,
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          isShowTitle
              ? FFlexible(
                  child: FContainer(
                    padding: EdgeInsets.only(left: 25, bottom: 5),

                    /// TODO:[Gavin] 多语言-UI-整合
                    width: (consultationController
                                    .patientInfoController.patientType ==
                                OrganizationPatientTypeEnum.Person
                            ? 95
                            : 125) +
                        (i18nBook.isCurrentChinese ? 0 : 60),
                    alignment: Alignment.centerLeft,
                    child: FText.rich(
                      TextSpan(children: [
                        TextSpan(text: title, style: labelStyle),
                        if (isRequired) ...[
                          TextSpan(
                            text: ' *',
                            style: labelStyle.copyWith(color: Colors.red),
                          )
                        ] else ...[
                          TextSpan(text: '')
                        ]
                      ]),
                    ),
                  ),
                  flex: 0,
                )
              : FSizedBox(
                  width: 25,
                ),
          widget,
        ],
      ),
    );
  }

  FWidget _buildSelect(List list, String key) {
    List<SelectModel> selectList = [];
    list.forEach(
      (element) {
        selectList.add(
          SelectModel(
            code: element,
            name: consultationController.getValues(element),
          ),
        );
      },
    );
    String selectedVal = controller.patientInfo[key] ?? '';
    final select = FSelect<SelectModel, String>(
      source: selectList,
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      hintText: i18nBook.remedical.select.t,
      value: selectList.any((e) => e.code == selectedVal) ? selectedVal : null,
      clearable: true,
      height: 38,
      optionLabelExtractor: (data) => data.name,
      optionValueExtractor: (data) => data.code,
      onSelectChanged: (value, index) {
        controller.patientInfo[key] = value;
        controller.editPatientInfo[key] = value;
      },
    );

    return FExpanded(child: select);
  }

  FWidget _buildPatientInfoInput(e) {
    var key = e['key'] ?? '';
    var value = controller.patientInfo[e['key']] ?? '';
    bool isIdCard = key == 'IdentityCard';
    return FBorderInput(
      hintSize: FFontSizes.H6,
      contentSize: FFontSizes.H6,
      maxLength: 20,
      height: 40,
      hintText: i18nBook.common.input.translate(
        [
          consultationController.getValues(
            e['key'],
          ),
        ],
      ),
      inputFormatters: ['AnimalInfoName', 'Breed', 'Name'].contains(key)
          ? []
          : [
              FilteringTextInputFormatter.allow(
                RegExp('^[a-z0-9A-Z]+'),
              ),
            ],
      borderColor: Color(0xffdcdfe6),
      onChanged: (value) {
        _validateIDCard(isIdCard, value);

        controller.editPatientInfo[e['key']] = value;
        controller.patientInfo[e['key']] = value;
      },
      controller: controller.getControllerByKey(key, value: value),
    );
  }

  @override
  void dispose() {
    controller.clearControllers();
    super.dispose();
  }

  void _validateIDCard(
    bool isIdCard,
    String value,
  ) {
    if (isIdCard && value.length == 18) {
      if (controller.validateIdNumber(value)) {
        controller.onIdCardChange(value);
      } else {
        PromptBox.toast(i18nBook.remedical.invalidIDInputError.t);
      }
    }
  }

  _buildAutoCreateDiagnosisTemplate() {
    consultationController.state.autoCreateExam = true;
    return FContainer(
        color: Colors.white,
        padding: EdgeInsets.only(
          top: 20,
          left: 45,
          right: 45,
          bottom: 30,
        ),
        child: FRow(
          children: [
            FText(
              i18nBook.remedical.isAutoCreateExam.t,
              style: TextStyle(fontSize: FFontSizes.H6),
            ),
            FSizedBox(
              width: 10,
            ),
            FRectangleCheckbox(
              value: true,
              isCheck: true,
              onChange: (dynamic value, isCheck) {
                consultationController.state.autoCreateExam = isCheck;
              },
            ),
          ],
        ));
  }
}

class _MobileLayout extends FisView<AddoreditPatientDialogController>
    implements FWidget {
  _MobileLayout(this.businessParent, {Key? key}) : super(key: key);

  ///父级节点
  final FPage businessParent;
  final consultationController = Get.find<ConsultationController>();

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      backgroundColor: Colors.white,
      appBar: FAppBar(
        backgroundColor: Color.fromARGB(255, 255, 255, 255),
        title: FText(
          i18nBook.remedical.patientDetail.t,
          style: TextStyle(
              fontSize: 16, color: Colors.black, fontWeight: FontWeight.bold),
        ),
        elevation: 0,
        centerTitle: true,
        leading: FIconButton(
          name: "back",
          businessParent: this.businessParent,
          icon: FIcon(Icons.arrow_back_ios_new,
              size: 20, color: Color.fromARGB(255, 0, 0, 0)),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: _Body(),
    );
  }
}

class _Body extends FisView<AddoreditPatientDialogController> {
  final consultationController = Get.find<ConsultationController>();

  @override
  FWidget build(BuildContext context) {
    final imageUrl = consultationController.patientInfoController.patientType ==
            OrganizationPatientTypeEnum.Person
        ? (controller.patientInfo['HeadImgUrl'] ?? '')
        : (controller.patientInfo['AnimalInfoHeadImgUrl'] ?? '');
    final isEmptyImage = imageUrl == null || imageUrl == '';
    final childImage = FContainer(
      child: SelectRow(
        title: i18nBook.organization.avatar.t,
        isImage: true,
        imageUrl: imageUrl,
        suffixIcon: FSizedBox(),
      ),
    );
    String buildAgeText(
      String ageUnits,
      String ageDay,
      String ageMonth,
      String ageWeek,
      String ageYear,
    ) {
      print(ageYear);

      switch (ageUnits) {
        case 'Year':
          return ageYear + i18nBook.remedical.years.t;
        case 'YearAndMonth':
          return ageYear +
              i18nBook.remedical.years.t +
              ageMonth +
              i18nBook.remedical.month.t;
        case 'MonthAndWeek':
          return ageMonth +
              i18nBook.remedical.month.t +
              ageWeek +
              i18nBook.remedical.week.t;
        case 'WeekAndDay':
          return ageWeek +
              i18nBook.remedical.week.t +
              ageDay +
              i18nBook.remedical.day.t;
        default:
          return i18nBook.remedical.notFill.t;
      }
    }

    return FContainer(
      color: Color.fromARGB(255, 236, 236, 236),
      child: FListView(
        shrinkWrap: true,
        children: [
          if (!isEmptyImage) ...[
            childImage,
          ],
          ...controller.patientKeyList.map((e) {
            if (e['key'] == 'AgeType') {
              return FContainer(
                child: SelectRow(
                  title: i18nBook.remedical.age.t,
                  value: buildAgeText(
                    controller.patientInfo['AgeUnits'],
                    controller.patientInfo['AgeDay'],
                    controller.patientInfo['AgeMonth'],
                    controller.patientInfo['AgeWeek'],
                    controller.patientInfo['AgeYear'],
                  ),
                  suffixIcon: FSizedBox(width: 0),
                ),
              );
            } else {
              return FContainer(
                child: SelectRow(
                  title: consultationController.getValues(e['key']),
                  value: (controller.patientInfo['${e['key']}'] == null ||
                          controller.patientInfo['${e['key']}']! == '')
                      ? i18nBook.remedical.notFill.t
                      : consultationController
                          .getValues(controller.patientInfo['${e['key']}']),
                  suffixIcon: FSizedBox(width: 0),
                ),
              );
            }
          }).toList(),
        ],
      ),
    );
  }
}
