import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.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/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/age_text.dart';
import 'package:flyinsono/pages/remedical/edit_patient_dialog/widgets/date_time.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/patient_age_input.dart';
import 'package:flyinsono/views/desktop/check_list_page_creation/widgets/check_list_page_item.dart';
// ignore: unused_import
import 'package:flyinsono/views/desktop/check_list_page_creation/widgets/select_patient.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
//import 'package:universal_html/html.dart';
import 'package:fis_common/index.dart';

import 'index.dart';

class CheckListPageCreation extends FStatelessWidget implements FPage {
  @override
  String get pageName => "CheckListPageCreation";

  /// 保存的检查列表
  late List selectCheckList = [];

  /// 滚动控制器
  final ScrollController _scrollController = ScrollController();

  final ScrollController _leftScrollController = ScrollController();
  final ScrollController _rightScrollController = ScrollController();
  final ScrollController _baseScrollController = ScrollController();
  final controller = Get.find<CheckListPageCreationController>();
  late CheckListPageCreationState state = controller.state;

  CheckListPageCreation({Key? key}) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      decoration: BoxDecoration(
        color: Color.fromRGBO(242, 242, 242, 1),
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
      ),
      margin: EdgeInsets.all(70),
      child: FColumn(
        children: [
          _buildCreateCheckTitle(),
          _buildCreateCheckOrganization(),
          _buildCreateCheckBody(context),
        ],
      ),
    );
  }

  FWidget _buildOnTapInput(String hintText, [Function? onTap]) {
    final FWidget child = FContainer(
      child: FObx(
        () => FBorderInput(
          contentSize: 16,
          maxLength: 20,
          borderColor: const Color.fromRGBO(230, 230, 230, 1),
          height: 38,
          hintSize: 16,
          readOnly: true,
          hintText: hintText,
          enableInteractiveSelection: false,
          controller: TextEditingController(text: state.patientInfo.name),
          onTap: () {
            onTap!();
          },
        ),
      ),
    );
    return child;
  }

  /// 检查的基础信息
  FWidget _buildBasicInformation(BuildContext context) {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FObx(
          () => _buildBasicInformationFWidgetItem(
            controller.state.patientType == OrganizationPatientTypeEnum.Person
                ? i18nBook.common.fullName.t
                : i18nBook.remedical.petName.t,
            _buildOnTapInput(
              '',
              () async {
                controller.openSelectPatient();
              },
            ),
            true,
          ),
        ),
        FObx(
          () => PatientAgeInput(controller.state.patientInfo),
        ),
        FRow(
          children: [
            FContainer(
              width: i18nBook.isCurrentChinese ? 80 : 130,
              child: FText(
                i18nBook.remedical.gender.t,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            FContainer(
              padding: EdgeInsets.symmetric(vertical: 10),
              height: 58,
              child: FObx(() {
                var source = controller.state.patientType ==
                        OrganizationPatientTypeEnum.Person
                    ? controller.sexSource
                    : controller.animalSexSource;
                return FColumn(
                  children: [
                    FConfigureSelect(
                      source: source,
                      onChanged: (value) {
                        state.patientInfo.sex = value;
                      },
                      value: source.any((element) =>
                              element.code == state.patientInfo.sex)
                          ? state.patientInfo.sex
                          : null,
                    ),
                  ],
                );
              }),
            ),
          ],
        ),
        FContainer(
          height: 50,
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              FContainer(
                /// TODO:[Gavin] 多语言-UI-整合
                width: i18nBook.isCurrentChinese ? 80 : 130,
                child: FText(
                  i18nBook.remedical.deliveryDevice.t,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              _buildEquipmentSelect(),
            ],
          ),
        ),
        FContainer(
          height: 50,
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              FContainer(
                /// TODO:[Gavin] 多语言-UI-整合
                width: i18nBook.isCurrentChinese ? 80 : 130,
                child: FText(
                  i18nBook.remedical.checkItem.t,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              FObx(
                () => _buildCheckItem(
                  controller.state.selectCheckList,
                ),
              ),
            ],
          ),
        ),
        FContainer(
          child: FObx(
            () => FAlwaysScrollListView(
              scrollController: _baseScrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView.builder(
                  controller: _baseScrollController,
                  shrinkWrap: true,
                  itemCount: controller.state.selectCheckList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return FContainer(
                      margin: EdgeInsets.only(
                        /// TODO:[Gavin] 多语言-UI-整合
                        left: i18nBook.isCurrentChinese ? 80 : 130,
                        bottom: 10,
                      ),
                      padding: EdgeInsets.only(
                        left: 14,
                        right: 5,
                      ),
                      height: 36,
                      width: 400,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Color.fromRGBO(
                            230,
                            230,
                            230,
                            1,
                          ),
                        ),
                        borderRadius: BorderRadius.all(
                          Radius.circular(4),
                        ),
                      ),
                      child: FRow(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          FText(
                            controller.getValues(
                                controller.state.selectCheckList[index]),
                            style: TextStyle(
                              fontSize: 16,
                            ),
                          ),
                          FIconButton(
                            name: "remove:$index",
                            businessParent: this,
                            onPressed: () {
                              selectCheckList.remove(
                                selectCheckList[index],
                              );
                              controller.state.selectCheckList =
                                  selectCheckList.toSet().toList();
                            },
                            icon: FIcon(
                              Icons.close,
                              size: 20,
                            ),
                          )
                        ],
                      ),
                    );
                  },
                ),
              )),
            ),
          ),
        ),
      ],
    );

    // });
  }

  /// 基础信息单元行
  FWidget _buildBasicInformationFWidgetItem(
    String title,
    FWidget value, [
    bool? isRequired = false,
  ]) {
    return FContainer(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 80 : 130,
            child: FText.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: title,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (isRequired!)
                    TextSpan(
                      text: '*',
                      style: TextStyle(
                        color: Colors.red,
                      ),
                    )
                ],
              ),
            ),
          ),
          value,
        ],
      ),
    );
  }

  ///  检查项目
  FWidget _buildCheckItem(List selectCheck) {
    final select = FObx(
      () => FSelect<SelectModel, String>(
        source: state.checkHasSelect,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        hintText: i18nBook.remedical.selectCheckItem.t,
        value: null,
        clearable: false,
        height: 36,
        width: 400,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          selectCheckList.add(value);
          if (value == 'Obstetrics') {
            state.contents['Obstetrics-GestationalAgeOrigin'] = 'LMP';
          }
          state.selectCheckList = selectCheckList.toSet().toList();
        },
      ),
    );

    return FExpanded(child: select);
  }

  /// 创建检查的主体
  FWidget _buildCreateCheckBody(BuildContext context) {
    return FExpanded(
      child: FContainer(
        margin: EdgeInsets.only(
          left: 15,
          right: 15,
          bottom: 15,
        ),
        color: Colors.white,
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildCreateCheckBodyPatientInfo(context),
            FContainer(
              height: 4,
              color: Color.fromRGBO(242, 242, 242, 1),
            ),
            _buildCreateCheckBodybutton(),
          ],
        ),
      ),
    );
  }

  /// 检查主体的按钮
  FWidget _buildCreateCheckBodybutton() {
    return FContainer(
      padding: EdgeInsets.only(top: 15, bottom: 15),
      color: Colors.white,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FElevatedButton(
            name: "save",
            businessParent: this,
            onPressed: () {
              controller.createRecordInfo();
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.submit.t),
          ),
          FSizedBox(
            width: 30,
          ),
          FOutlinedButton(
            name: "back",
            businessParent: this,
            onPressed: () async {
              router.back();
            },
            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: FTheme.ins.colorScheme.primary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 检查主体的病人信息
  FWidget _buildCreateCheckBodyPatientInfo(BuildContext context) {
    return FExpanded(
      child: FRow(
        children: [
          FContainer(
            width: 400,
            margin: EdgeInsets.symmetric(
              horizontal: 30,
              vertical: 20,
            ),
            child: FAlwaysScrollListView(
              scrollController: _leftScrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView(
                  controller: _leftScrollController,
                  children: [
                    _buildBasicInformation(context),
                    FRow(
                      children: [
                        FContainer(
                          /// TODO:[Gavin] 多语言-UI-整合
                          width: i18nBook.isCurrentChinese ? 80 : 130,
                          height: 40,
                          alignment: Alignment.centerLeft,
                          child: FText(
                            i18nBook.remedical.checkDoctor.t,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        FContainer(
                          child: FText(_generatorDoc()),
                        ),
                      ],
                    ),
                  ],
                ),
              )),
            ),
          ),
          FContainer(
            width: 15,
            color: Color.fromRGBO(242, 242, 242, 1),
          ),
          FExpanded(
            child: FContainer(
              child: FListView(
                controller: _scrollController,
                children: [
                  _buildRightRow(context),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 创建检查的组织部分
  FWidget _buildCreateCheckOrganization() {
    return FContainer(
      color: Colors.white,
      margin: EdgeInsets.only(left: 15, right: 15, bottom: 5, top: 15),
      height: 40,
      child: FRow(
        children: [
          FExpanded(
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildTabs(
                  i18nBook.remedical.time.t,
                  DateTime.now().toString().substring(0, 16),
                ),
                if (Store.user.rootOrganizationCode.isNotNullOrEmpty) ...[
                  _buildTabs(
                    i18nBook.organization.department.t,
                    controller
                        .consultationRecordViewController.organizationName,
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 创建检查头部
  FWidget _buildCreateCheckTitle() {
    return FContainer(
      height: 50,
      decoration: BoxDecoration(
        color: FTheme.ins.colorScheme.primary,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
      child: FAlign(
        alignment: Alignment.centerLeft,
        child: FContainer(
          margin: EdgeInsets.only(left: 15),
          child: FText(
            i18nBook.remedical.createCheck.t,
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
            ),
          ),
        ),
      ),
    );
  }

  /// 下发设备
  FWidget _buildEquipmentSelect() {
    /// 上级机构
    final select = FObx(() => FSelect<SelectModel, String>(
          source: state.deviceOptions,
          hintText: i18nBook.remedical.selectDeliveryDevice.t,
          value: state.deviceCode,
          fontFamily: FTheme.ins.localeSetting.fontFamily,
          clearable: true,
          height: 36,
          width: 400,
          optionLabelExtractor: (data) => data.name,
          optionValueExtractor: (data) => data.code,
          onSelectChanged: (value, index) {
            if (value == null) {
              state.deviceCode = null;
              return;
            }
            state.deviceCode = value;
          },
        ));

    return FExpanded(child: select);
  }

  FWidget _buildRightRow(BuildContext context) {
    final child = FObx(
      () => FContainer(
        padding: EdgeInsets.all(30),
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FAlwaysScrollListView(
              scrollController: _rightScrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView.builder(
                  controller: _rightScrollController,
                  shrinkWrap: true,
                  itemCount: state.selectCheckList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return FColumn(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FText(
                          controller
                              .getValues(state.selectCheckList[index])
                              .toString(),
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        FSizedBox(
                          height: 20,
                        ),
                        FObx(
                          () => CheckListPageItem(
                            selectCheckListItem: state.selectCheckList[index],
                          ),
                        ),
                        FDivider(),
                      ],
                    );
                  },
                ),
              )),
            ),
          ],
        ),
      ),
    );
    return FColumn(
      children: [child],
    );
  }

  FWidget _buildTabs(String name, String value) {
    return FRow(
      children: [
        FSizedBox(
          width: 30,
        ),
        FContainer(
          child: FText(
            name,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FSizedBox(
          width: 30,
        ),
        FContainer(
          child: FText(value),
        ),
      ],
    );
  }

  String _generatorDoc() {
    return ((Store.user.displayName.isEmpty)
        ? i18nBook.homePage.notYet.t
        : Store.user.displayName);
  }
}

class _MobileLayout extends FisView<CheckListPageCreationController>
    implements FWidget {
  ///父级节点
  final FPage businessParent;

  const _MobileLayout(this.businessParent, {Key? key}) : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return FContainer();
  }
}
