import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/models.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/widgets/mobile/record_refer_mobile_select.dart';
import 'package:get/get.dart';

/// PC端转诊输入框
class RecordReferralMobileApplication extends FStatelessWidget
    implements FInteractiveContainer {
  final String patientName;
  final String? recordCode;
  // final consultationController = Get.find<ConsultationController>();
  final controller = Get.find<ConsultationRecordViewController>();
  final textFocusNode = FocusNode();
  final fontStyle = TextStyle(
    fontSize: 14,
  );
  @override
  final String pageName;
  RecordReferralMobileApplication(this.patientName, this.recordCode,
      {this.pageName = 'RecordReferralMobileApplication'});

  @override
  FWidget build(BuildContext context) {
    return _buildReferral();
  }

  FWidget _buildReferralItem(String title, FWidget referralItem,
      [bool? isRequired]) {
    return FContainer(
      margin: EdgeInsets.symmetric(
        vertical: 15,
      ),
      child: FRow(
        children: [
          FContainer(
            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 100 : 130,
            child: FRow(
              mainAxisSize: MainAxisSize.min,
              children: [
                FExpanded(
                  child: FText(
                    title,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                FSizedBox(
                  width: 20,
                  child: isRequired ?? false
                      ? FText(
                          '*',
                          style: TextStyle(color: Colors.red),
                        )
                      : FSizedBox(),
                )
              ],
            ),
          ),
          FExpanded(
            child: referralItem,
          ),
        ],
      ),
    );
  }

  FWidget _buildReferral() {
    return FGestureDetector(
      name: "unfocus",
      businessParent: this,
      onTap: () {
        textFocusNode.unfocus();
      },
      child: FColumn(
        children: [
          FExpanded(
            child: FSingleChildScrollView(
              child: FContainer(
                padding: EdgeInsets.only(
                  top: 25,
                  left: 20,
                  right: 20,
                ),
                child: FColumn(
                  children: [
                    _buildReferralItem(
                      i18nBook.remedical.patientDisplayName.t,
                      FText(patientName),
                    ),
                    _buildReferralItem(
                      i18nBook.remedical.transferOutAgency.t,
                      FText(
                        controller.organizationName,
                      ),
                    ),
                    _buildReferralItem(
                      i18nBook.remedical.transferSubjectMatter.t,
                      FTextField(
                        maxLines: 3,
                        maxLength: 100,
                        focusNode: textFocusNode,
                        decoration: InputDecoration(
                          hintText: i18nBook.common.input.translate(
                              [i18nBook.remedical.transferSubjectMatter.t]),
                          hintStyle: TextStyle(
                            fontSize: 16,
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.5),
                              width: 0.5,
                              style: BorderStyle.solid,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: FTheme.ins.colorScheme.primary,
                              width: 0.5,
                              style: BorderStyle.solid,
                            ),
                          ),
                          filled: true,
                        ),
                        controller: TextEditingController(
                          text: controller.subjectMatter,
                        ),
                        onChanged: (val) => controller.subjectMatter = val,
                      ),
                      true,
                    ),
                    _buildReferralItem(
                      i18nBook.remedical.transferOrganization.t,
                      FisBuilder<ConsultationRecordViewController>(
                          id: 'transfer_organization',
                          builder: (_) {
                            return RecordReferSelectSheet<
                                FSelectOptionModel<String>, String>(
                              hintText: i18nBook.common.Select.t,
                              source: controller.referOrg,
                              value: controller.referralOrganizationCode,
                              tipTitle:
                                  i18nBook.remedical.pleaseSelect.translate(
                                [i18nBook.remedical.transferOrganization.t],
                              ),
                              optionLabelExtractor: (data) => data.title,
                              optionValueExtractor: (data) => data.value,
                              inkWellTitle: i18nBook.homePage.notYet.t +
                                  i18nBook.remedical.transferOrganization.t,
                              onChange: (value) async {
                                controller.referralOrganizationCode = '';
                                await controller.getUserListAsync(value!);
                                controller.referralOrganizationCode = value;
                                controller.referralUserCode = null;
                                controller.update([
                                  'transfer_organization',
                                  'transfer_doctor'
                                ]);
                              },
                            );
                          }),
                      true,
                    ),
                    FisBuilder<ConsultationRecordViewController>(
                        id: 'transfer_doctor',
                        builder: (_) {
                          final List<UserDoctorModel> referUserList = controller
                              .referUserList
                              .where(
                                  (element) => element.code != Store.user.code)
                              .toList();
                          return _buildReferralItem(
                            i18nBook.remedical.transferDoctor.t,
                            RecordReferSelectSheet<UserDoctorModel, String>(
                              hintText: i18nBook.common.Select.t,
                              tipTitle:
                                  i18nBook.remedical.pleaseSelect.translate(
                                [i18nBook.remedical.transferDoctor.t],
                              ),
                              optionLabelExtractor: (data) => data.name,
                              optionValueExtractor: (data) => data.code,
                              source: referUserList,
                              inkWellTitle:
                                  controller.referralOrganizationCode == '' ||
                                          controller.referralOrganizationCode ==
                                              null
                                      ? i18nBook.remedical.select.t +
                                          i18nBook
                                              .remedical.transferOrganization.t
                                      : i18nBook.remedical.hasNoChooseAgain.t,
                              value: controller.referralUserCode,
                              isCustomMade: true,
                              specialWidget: (data) =>
                                  _buildSpecialWidget(data),
                              onChange: (value) {
                                controller.referralUserCode = value!;
                                controller.update(['transfer_doctor']);
                              },
                            ),
                            true,
                          );
                        }),
                    _buildReferralItem(
                      i18nBook.remedical.transferApply.t,
                      FText(Store.user.displayName),
                    ),
                  ],
                ),
              ),
            ),
          ),
          _buildButtomOperate(),
        ],
      ),
    );
  }

  FWidget _buildSpecialWidget(UserDoctorModel userDoctor) {
    return FRow(
      children: [
        _buildImage(userDoctor.headImageUrl),
        FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            FText(
              userDoctor.name,
              style: fontStyle,
            ),
            FText(
              userDoctor.roleName ?? '',
              style: fontStyle,
            ),
            if (userDoctor.fieldList!.isNotEmpty)
              FText(
                i18nBook.user.skilledAreaWithDevider.t +
                    userDoctor.fieldList!.join("，"),
                style: fontStyle,
              ),
          ],
        )
      ],
    );
  }

  FWidget _buildImage(String? isImage) {
    var child;
    isImage!.isEmpty
        ? child = FImage.asset(
            'assets/images/avatar_man.png',
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          )
        : child = FImage.network(
            isImage,
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          );
    return FContainer(
      margin: EdgeInsets.only(
        right: 15,
      ),
      child: FClipRRect(
        borderRadius: BorderRadius.circular(
          25,
        ),
        child: child,
      ),
    );
  }

  FWidget _buildButtomOperate() {
    return FContainer(
      height: 50,
      alignment: Alignment.center,
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildButtomOperateItem(
            onTap: () {
              controller.initReferStatus();
            },
            decoration: BoxDecoration(
              border: Border.all(width: 0.5, color: Colors.grey),
            ),
            title: i18nBook.common.cancel.t,
          ),
          _buildButtomOperateItem(
            onTap: () => controller.submitRefer(
              controller.patientCode,
              recordCode,
            ),
            backgroundColor: FTheme.ins.colorScheme.primary,
            textColor: Colors.white,
            title: i18nBook.common.submit.t,
          ),
        ],
      ),
    );
  }

  FWidget _buildButtomOperateItem({
    required String title,
    required Function onTap,
    Color? backgroundColor,
    Color? textColor,
    BoxDecoration? decoration,
  }) {
    return FExpanded(
      child: FContainer(
        color: backgroundColor,
        decoration: decoration,
        child: FInkWell(
          onTap: () {
            onTap();
          },
          child: FCenter(
            child: FText(
              title,
              style: TextStyle(
                color: textColor,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
