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/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/organization/org_info/state.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/state.dart';
import 'package:get/get.dart';

/// PC端转诊输入框
class ReferralApplication extends FStatelessWidget
    implements FInteractiveContainer {
  final PatientInfo patientInfo;
  @override
  final String pageName;
  final consultationController = Get.find<ConsultationController>();
  final controller = Get.find<ConsultationController>();

  ReferralApplication(this.patientInfo,
      {this.pageName = 'ReferralApplication'});

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      child: _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 ? 150 : 200,
            child: FRow(
              children: [
                FText(title),
                isRequired ?? false
                    ? FText(
                        '*',
                        style: TextStyle(color: Colors.red),
                      )
                    : FSizedBox(),
              ],
            ),
          ),
          FExpanded(
            child: referralItem,
          ),
        ],
      ),
    );
  }

  /// 转入机构
  FWidget _buildReferOrg() {
    final controller = Get.find<ConsultationController>();
    final state = controller.state;
    final referOrg = FObx(
      () => FSelect<OrgModel, String>(
        source: state.referOrg,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        hintText: i18nBook.remedical.pleaseSelect.translate(
          [i18nBook.remedical.transferOrganization.t],
        ),
        value: controller.state.referralOrganizationCode,
        clearable: false,
        height: 40,
        width: 400,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          controller.state.referralOrganizationCode = '';
          controller.inspectionRecordsController.getUserListAsync(value!);
          controller.state.referralUserCode = null;
          controller.state.referralOrganizationCode = value;
        },
      ),
    );
    return referOrg;
  }

  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,
      ),
    );
  }

  String _buildRoleName(String roleCode) {
    final index = controller.state.userRoleList.indexWhere(
      (x) => x.code == roleCode,
    );
    if (index == -1) {
      return '';
    }
    return controller.state.userRoleList[index].name;
  }

  /// 转入医生
  FWidget _buildReferDoctor() {
    final state = controller.state;
    final fontStyle = TextStyle(
      fontSize: 14,
    );
    final referOrg = FObx(() {
      final List<UserDoctorModel> referUserList =
          state.referUserList.where((element) {
        return element.code != Store.user.code;
      }).toList();
      return FSelect<UserDoctorModel, String>(
        source: referUserList,
        hintText: i18nBook.remedical.pleaseSelect.translate(
          [i18nBook.remedical.transferDoctor.t],
        ),
        value: controller.state.referralUserCode,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        clearable: false,
        height: 40,
        specialWidgetHeight: 80,
        width: 400,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          controller.state.referralUserCode = value!;
        },
        specialWidget: (data) => FContainer(
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                width: 0.5,
                color: FTheme.ins.colorScheme.line,
              ),
            ),
          ),
          child: FRow(
            children: [
              _buildImage(data.headImageUrl),
              FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  FText(
                    data.name,
                    style: fontStyle,
                  ),
                  if (data.roleCodes!.isNotEmpty)
                    FText(
                      _buildRoleName(
                        data.roleCodes![0],
                      ),
                      style: fontStyle,
                    ),
                  if (data.fieldList!.isNotEmpty)
                    FText(
                      i18nBook.user.skilledAreaWithDevider.t +
                          data.fieldList!.join("，"),
                      style: fontStyle,
                    ),
                ],
              )
            ],
          ),
        ),
      );
    });
    return referOrg;
  }

  FWidget _buildReferral() {
    return FColumn(
      children: [
        FExpanded(
          child: FContainer(
            padding: EdgeInsets.only(
              top: 25,
              left: 25,
              right: 25,
            ),
            child: FColumn(
              children: [
                _buildReferralItem(
                  i18nBook.remedical.patientDisplayName.t,
                  FText(patientInfo.name ?? ''),
                ),
                _buildReferralItem(
                  i18nBook.remedical.transferOutAgency.t,
                  FText(
                    consultationController
                        .patientInfoController.organizationName,
                  ),
                ),
                _buildReferralItem(
                  i18nBook.remedical.transferSubjectMatter.t,
                  FTextField(
                    maxLines: 3,
                    maxLength: 100,
                    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.state.subjectMatter,
                    ),
                    onChanged: (val) => controller.state.subjectMatter = val,
                  ),
                  true,
                ),
                _buildReferralItem(
                  i18nBook.remedical.transferOrganization.t,
                  _buildReferOrg(),
                  true,
                ),
                _buildReferralItem(
                  i18nBook.remedical.transferDoctor.t,
                  _buildReferDoctor(),
                  true,
                ),
                _buildReferralItem(
                  i18nBook.remedical.transferApply.t,
                  FText(Store.user.displayName),
                ),
              ],
            ),
          ),
        ),
        _buildButtomOperate(),
      ],
    );
  }

  FWidget _buildButtomOperate() {
    var patientCode = patientInfo.patientCode;
    return FContainer(
      height: 80,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(
            width: 0.5,
            color: FTheme.ins.colorScheme.line,
          ),
        ),
      ),
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          FElevatedButton(
            businessParent: this,
            name: "submitRefer:$patientCode",
            onPressed: () {
              CommonUtil.debounce(
                () => controller.inspectionRecordsController.submitRefer(
                  patientCode,
                  patientInfo.referralRecordCode ?? '',
                ),
              );
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.submit.t),
          ),
          FSizedBox(
            width: 20,
          ),
          FOutlinedButton(
            name: "cleanState",
            businessParent: this,
            onPressed: () {
              controller.inspectionRecordsController.cleanState();
              router.back();
              controller.state.referTab = 0;
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                Colors.white,
              ),
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(
              i18nBook.common.cancel.t,
              style: TextStyle(
                color: Color.fromRGBO(
                  61,
                  146,
                  252,
                  1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
